ImageMagick 是 Linux 下最強大的命令行圖片處理工具箱。本文實戰演示 CentOS 安裝配置,並提供批量壓縮、格式轉換、添加水印的生產級 Shell 腳本。
# CentOS/RHEL
yum install -y ImageMagick
# Ubuntu/Debian
apt install -y imagemagick
# 驗證
convert -version
# Version: ImageMagick 6.9.10-68 Q16 x86_64 2021-10-14
| 任務 | 命令範例 |
|---|---|
| 壓縮尺寸 | convert input.jpg -resize 800x600 output.jpg |
| 按比例壓縮 | convert input.jpg -resize 50% output.jpg |
| 質量壓縮 | convert input.jpg -quality 85 output.jpg |
| 格式轉換 | convert input.png output.jpg |
| 添加文字水印 | convert input.jpg -font DejaVu-Sans -pointsize 24 -draw "gravity southeast fill black text 10,10 'Watermark' fill white text 11,11 'Watermark'" output.jpg |
| 添加圖片水印 | convert input.jpg watermark.png -gravity southeast -composite output.jpg |
#!/bin/bash
# compress_images.sh - 批量壓縮當前目錄下所有 jpg/png/gif
# 用法:./compress_images.sh [目標寬度] [質量]
TARGET_WIDTH=${1:-1920}
QUALITY=${2:-85}
mkdir -p compressed
shopt -s nocaseglob
for img in *.jpg *.jpeg *.png *.gif; do
[ -f "$img" ] || continue
echo "Processing: $img"
convert "$img" -resize "${TARGET_WIDTH}x>" -quality "$QUALITY" "compressed/${img%.*}_w${TARGET_WIDTH}.${img##*.}"
done
echo "Done. Compressed images in ./compressed/"
#!/bin/bash
# bmp2jpg.sh - 遞歸轉換 BMP 為 JPG
find . -type f -iname "*.bmp" | while read bmp_file; do
jpg_file="${bmp_file%.*}.jpg"
echo "Converting: $bmp_file -> $jpg_file"
convert "$bmp_file" -quality 90 "$jpg_file" && rm "$bmp_file"
done
#!/bin/bash
# watermark.sh - 為圖片添加文字水印
WATERMARK_TEXT="© YourCompany 2024"
FONT_SIZE=20
COLOR="rgba(255,255,255,0.7)"
find . -type f \( -iname "*.jpg" -o -iname "*.png" \) | while read img; do
echo "Watermarking: $img"
convert "$img" -font DejaVu-Sans -pointsize $FONT_SIZE \
-fill "$COLOR" -gravity southeast \
-annotate +10+10 "$WATERMARK_TEXT" \
"$img.watermarked" && mv "$img.watermarked" "$img"
done
find . -name "*.jpg" | xargs -P 4 -I {} convert {} -resize 50% {}mogrify 就地修改(無輸出文件開銷)GNU Parallelconvert: not authorized → 編輯 /etc/ImageMagick-6/policy.xml 移除 <policy domain="coder" rights="none" pattern="PDF" /> 等限制MAGICK_MEMORY_LIMIT=2GiB MAGICK_MAP_LIMIT=4GiBdejavu-sans-fonts 或指定存在字體路徑掌握 ImageMagick 腳本化能力,讓圖片批量處理從繁瑣走向自動化。