ImageMagick 是命令列圖片處理瑞士刀,支援 200+ 格式,提供格式轉換、縮放、裁切、水印、色彩空間轉換等功能。本文示範 CentOS/Ubuntu 安裝與批次處理腳本,涵蓋 JPEG/PNG/GIF/BMP 多格式壓縮與轉檔。
# CentOS/RHEL/Fedora
yum install ImageMagick
# Ubuntu/Debian/Mint
sudo apt-get install imagemagick
# 驗證
convert -version
# 單檔縮放至 300x300 (保持比例)
convert input.jpg -resize 300x300 output.jpg
# 縮放至 50% 大小
convert input.jpg -resize 50% output.jpg
# 強制固定尺寸 (可能變形)
convert input.jpg -resize 300x300! output.jpg
# 品質調整 (JPEG)
convert input.jpg -quality 85 output.jpg
#!/bin/bash
# resize-images.sh
for img in $(find . -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" -o -iname "*.gif"); do
echo "Processing: $img"
convert -resize 85%x85% "$img" "${img%.*}_resized.${img##*.}"
mv "${img%.*}_resized.${img##*.}" "$img"
done
#!/bin/bash
# bmp2jpg.sh
for img in $(find . -iname "*.bmp"); do
_imglower=$(echo "$img" | tr '[:upper:]' '[:lower:]')
_basename=$(basename "$_imglower" .bmp)
_dirname=$(dirname "$img")
_basefullname="${_dirname}/${_basename}.jpg"
convert "$img" "$_basefullname"
rm "$img"
echo "Converted: $_basefullname"
done
#include
#include
int main() {
printf("Please install ImageMagick before run this programme\n");
system("mkdir -p small");
system("cp *.jpg ./small/");
system("find ./small -name '*.jpg' -exec convert -resize 300x300 {} {} \\;");
system("pwd");
system("rename 's/.jpg$/_small.jpg/' small/*.jpg");
printf("Convert pictures finished\n");
return 0;
}
注意:C 程式調用 system() 效能較差且有注入風險,生產環境建議直接使用 Shell 腳本或 Python (wand/subprocess)。
| 需求 | 指令範例 |
|---|---|
| 添加文字水印 | convert input.jpg -gravity southeast -pointsize 24 -draw "text 10,10 'Watermark'" output.jpg |
| 添加圖片水印 | convert input.jpg watermark.png -gravity southeast -composite output.jpg |
| 灰階轉換 | convert input.jpg -colorspace Gray output.jpg |
| 銳化 | convert input.jpg -sharpen 0x1 output.jpg |
| 去除 EXIF | convert input.jpg -strip output.jpg |
| 建立縮圖聯絡表 | montage *.jpg -geometry 100x100+5+5 contact.jpg |