Files
Shell-Scripts/convert_and_copy_exif.sh
T

92 lines
3.1 KiB
Bash
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env bash
set -euo pipefail
# 使用:convert_and_copy_exif.sh /path/to/source_dir [target_dir]
# SOURCE_DIR 必填:包含原始带 EXIF 的原图的文件夹
# TARGET_DIR 可选:要处理的文件夹(默认当前目录)
if [[ "${1:-}" == "" ]]; then
echo "Usage: $0 /path/to/source_dir [target_dir]" >&2
exit 2
fi
SOURCE_DIR="$1"
TARGET_DIR="${2:-.}"
# 依赖检查
if ! command -v exiftool >/dev/null 2>&1; then
echo "exiftool not found. Please install exiftool." >&2
exit 3
fi
# prefer magick if available (ImageMagick v7), otherwise use convert
if command -v magick >/dev/null 2>&1; then
IM_CONVERT="magick"
elif command -v convert >/dev/null 2>&1; then
IM_CONVERT="convert"
else
echo "ImageMagick (magick or convert) not found. Please install it." >&2
exit 4
fi
# 处理扩展名列表(大小写无关)
shopt -s nullglob
mapfile -t files < <(find "$TARGET_DIR" -maxdepth 1 -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" -o -iname "*.webp" -o -iname "*.heic" -o -iname "*.tif" -o -iname "*.tiff" -o -iname "*.bmp" -o -iname "*.gif" \) -print0 | xargs -0 -I{} printf '%s\n' "{}")
if [[ ${#files[@]} -eq 0 ]]; then
echo "No image files found in target directory: $TARGET_DIR"
exit 0
fi
for srcpath in "${files[@]}"; do
# 生成目标 jpg 文件路径(放在同一目录,保留原文件不覆盖)
dir=$(dirname -- "$srcpath")
base=$(basename -- "$srcpath")
name_noext="${base%.*}"
target_jpg="$dir/${name_noext}.jpg"
# 如果源本身就是 .jpg/.jpeg,则将 target_jpg 指向原文件(不重复转码)
ext="${base##*.}"
lower_ext="${ext,,}"
if [[ "$lower_ext" == "jpg" || "$lower_ext" == "jpeg" ]]; then
target_jpg="$srcpath"
echo "Skipping convert (already jpg): $srcpath"
else
# 转码为 jpg(如果目标存在则跳过转码)
if [[ -f "$target_jpg" ]]; then
echo "Target JPG already exists, skipping convert: $target_jpg"
else
echo "Converting: $srcpath -> $target_jpg"
# -strip 在这里不使用,因为后面要用 exiftool 覆盖;保留像素信息
"$IM_CONVERT" "$srcpath" -quality 95 "$target_jpg"
if [[ $? -ne 0 ]]; then
echo "Convert failed for $srcpath" >&2
continue
fi
fi
fi
# 在 SOURCE_DIR 中查找同名原图(任意扩展名),优先返回第一个匹配
found_src=""
while IFS= read -r -d $'\0' cand; do
found_src="$cand"
break
done < <(find "$SOURCE_DIR" -type f -iname "${name_noext}.*" -print0)
if [[ -z "$found_src" ]]; then
echo "No matching source with same name in $SOURCE_DIR for: $name_noext" >&2
continue
fi
# 使用 exiftool 按提供的命令模板:先清掉再从 found_src 拷贝所有标签,设置 Artist 和 清空 UserComment,Orientation Normal
echo "Copying EXIF from $found_src -> $target_jpg"
exiftool -overwrite_original -all= -tagsFromFile "$found_src" "-all:all>all:all" -Artist="Paul" -UserComment= -Orientation=Normal "$target_jpg" >/dev/null 2>&1
if [[ $? -eq 0 ]]; then
echo "EXIF copied: $target_jpg"
else
echo "Failed to copy EXIF for $target_jpg" >&2
fi
done
echo "Done."