只压缩大于 300x300 的图片,用
convert 压缩到 300x300 并设置质量为 90,但如果压缩后文件比原文件大,就舍弃压缩文件。
#!/bin/bash
# 要处理的根目录
DIR="./" # 可修改为你的目录
# 遍历所有图片文件(jpg, jpeg, png, gif),递归子目录
find "$DIR" -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" -o -iname "*.gif" \) -print0 | while IFS= read -r -d '' file; do
ext="${file##*.}"
ext="${ext,,}"
# 获取图片宽高
dimensions=$(identify -format "%w %h" "$file[0]" 2>/dev/null)
if [ -z "$dimensions" ]; then
echo "无法识别: $file"
continue
fi
# 读取宽高
width=$(echo "$dimensions" | awk '{print $1}')
height=$(echo "$dimensions" | awk '{print $2}')
# 确保宽高是整数
if ! [[ "$width" =~ ^[0-9]+$ ]] || ! [[ "$height" =~ ^[0-9]+$ ]]; then
echo "宽高非法: $file ($dimensions)"
continue
fi
# 只处理宽高大于300的图片
if [ "$width" -le 300 ] && [ "$height" -le 300 ]; then
continue
fi
echo "处理: $file ($width x $height)"
# 创建临时文件
case "$ext" in
gif)
tmpfile=$(mktemp /tmp/compressed_XXXXXX.gif)
;;
*)
tmpfile=$(mktemp /tmp/compressed_XXXXXX.jpg)
;;
esac
# 压缩到 300x300,质量 90
convert "$file" -resize 300x300\> -quality 90 "$tmpfile"
# 检查压缩文件是否存在且大小 > 0
tmp_size_bytes=$(stat -c%s "$tmpfile" 2>/dev/null | tr -d '[:space:]' | grep -o '[0-9]\+')
if [ -z "$tmp_size_bytes" ] || [ "$tmp_size_bytes" -eq 0 ]; then
echo "压缩文件无效或为空,保留原文件: $file"
rm -f "$tmpfile"
continue
fi
# 获取原文件大小
orig_size=$(stat -c%s "$file" | tr -d '[:space:]' | grep -o '[0-9]\+')
new_size=$tmp_size_bytes
# 文件大小比较
if [ -z "$orig_size" ]; then
echo "获取原文件大小失败: $file"
rm -f "$tmpfile"
continue
fi
if [ "$new_size" -ge "$orig_size" ]; then
# 压缩文件比原文件大或一样,舍弃
rm -f "$tmpfile"
echo "保留原文件: $file"
else
# 替换原文件
mv "$tmpfile" "$file"
percent=$(( (orig_size - new_size) * 100 / orig_size ))
echo "替换文件: $file (原大小 $orig_size -> 新大小 $new_size, 节省 $percent%)"
fi
done