跳到正文
DEV Community· printfapps·· 14 小時前AI 評分48

如何用 ImageMagick 命令列為數千張圖片加上浮水印

Add a watermark to thousands of images with ImageMagick from the command line

AI 導讀

文章展示如何用 ImageMagick 命令列批次為圖片加上浮水印,並透過 cmdbook 把腳本中可變的資料設為表單欄位。設定每次同時處理 20 張圖片後,2,000 張圖片在作者的 Mac 上用時 56 秒;原始圖片不會被修改,新增圖片可在再次執行時處理。

正文

You have a folder of photos, with subfolders, and every one needs a "© 2026 Jane" in the corner before it goes online.

How do you do it?

You ask an AI. It gives you mogrify, which is short, but it overwrites your originals. You ask for a version that saves copies. Then you ask for a loop over the subfolders, and one that doesn't break on Bob's photo 1.JPG.

It works, slowly. A plain loop does one image at a time: 2,000 photos take about 9 minutes on my Mac. So you ask how to run several at once, and get xargs -P. Now it's even slower: each ImageMagick also starts a thread per core, and 20 of them fight over the CPU. Mine did 480 photos in 10 minutes. One more line fixes it: MAGICK_THREAD_LIMIT=1.

You save the script somewhere: a Markdown note, or a watermark.sh file. Next time the text is different, or the corner, and you have to find the script and edit the middle of a long magick line.

With cmdbook, the script has one place to live, and it gets a GUI for free.

The folder, the text, the corner and the opacity become fields in a form

Here's how

1. Save the script once. Create a command in cmdbook and paste the script (it's at the end).

2. Mark what changes. The folder, the text, the corner and the opacity become placeholders:

DIR="{{prompt:folder}}"
TEXT="{{prompt:text?© Your Name}}"
POSITION={{prompt:position?southeast|southwest|northeast|northwest|center}}
OPACITY={{prompt:opacity?60|40|80|100}}

A list like southeast|southwest|... becomes a dropdown. The first one is the default.

3. Click Run. cmdbook shows a form. Drag the folder onto it, type your text, pick a corner, press Enter.

4. Watch it run.

Watermarking with 20 jobs at a time...
  failed: ./products/broken.png
  500 done
  1000 done
  1500 done
  2000 done

Watermarked 2000, skipped 0 (already done), failed 1.
Saved in: /Users/jane/Photos/watermarked

2,000 photos (most of them 12 megapixels) in 56 seconds on my Mac. Your originals are not touched: the results go to a watermarked folder, with the same subfolders. Run it again after adding photos, and only the new ones are done.

Next time, your folder, text and corner are already filled in.

That's all a script needs to get a GUI: mark the parts that change. The rest is the script you already have.

Try cmdbook here: printf.app/cmdbook

The full script (macOS, needs ImageMagick)

DIR="{{prompt:folder}}"
TEXT="{{prompt:text?© Your Name}}"
POSITION={{prompt:position?southeast|southwest|northeast|northwest|center}}
OPACITY={{prompt:opacity?60|40|80|100}}

export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"
command -v magick >/dev/null || { echo "ImageMagick not found. Install it: brew install imagemagick"; exit 1; }
cd "$DIR" || exit 1

# Originals are never changed: results go to a "watermarked" folder,
# with the same subfolders.
export OUTDIR="watermarked" POSITION
export TEXT="${TEXT//%/%%}"                       # % is special in ImageMagick text
export ALPHA=$(awk -v o="$OPACITY" 'BEGIN { print o / 100 }')
export HALF=$(awk -v o="$OPACITY" 'BEGIN { print o / 200 }')   # thin, lighter outline so it reads on light images too
JOBS=$(sysctl -n hw.ncpu 2>/dev/null || nproc)    # one ImageMagick per CPU core
export MAGICK_THREAD_LIMIT=1                      # ...each using one thread, or they fight over the cores

echo "Watermarking with $JOBS jobs at a time..."
find . -path "./$OUTDIR" -prune -o -type f \( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' -o -iname '*.webp' \) -print0 |
  xargs -0 -n 20 -P "$JOBS" /bin/bash -c '
    for IN; do
      OUT="$OUTDIR/${IN#./}"
      if [ -e "$OUT" ] && [ "$OUT" -nt "$IN" ]; then echo skip; continue; fi
      mkdir -p "$(dirname "$OUT")"
      # Text size follows the image: 1/25 of the shorter side.
      S=$(magick identify -format "%[fx:min(w,h)]" "$IN[0]" 2>/dev/null) || { echo "fail $IN"; continue; }
      if magick "$IN" -auto-orient -gravity "$POSITION" -pointsize $((S / 25)) \
           -fill "rgba(255,255,255,$ALPHA)" -stroke "rgba(0,0,0,$HALF)" -strokewidth $((S / 1500 + 1)) \
           -annotate +$((S / 40))+$((S / 40)) "$TEXT" "$OUT" 2>/dev/null; then
        echo ok
      else
        rm -f "$OUT"; echo "fail $IN"
      fi
    done' _ |
  awk '$1 == "ok" { ok++ } $1 == "skip" { skip++ } $1 == "fail" { fail++; sub(/^fail /, ""); print "  failed: " $0 }
       (ok + skip + fail) % 500 == 0 { printf "  %d done\n", ok + skip + fail }
       END { printf "\nWatermarked %d, skipped %d (already done), failed %d.\nSaved in: %s/watermarked\n", ok, skip, fail, ENVIRON["PWD"]; exit fail > 0 }'

來源:DEV Community · dev.to