所以我有一堆图像想要垂直附加:
convert *.png -append output.png
但是我遇到了两个问题:
如何居中对齐所有图像并指定它们之间的间距?
我的方法是使用 shell 脚本,如下所示:
1. Run a loop over all your images and find the width of the widest (using ImageMagick `identify`) - say 8 to 10 lines of shell script
2. Create a transparent "spacer image" the same width as the widest image and the height you want for vertically spacing images - one line of shell script
3. Run a loop over all your images first adding the transparent "spacer" to the bottom of the existing output image then compositing images that are narrower than your widest image onto a transparent background the width of your widest image - then appending that to the output image - maybe 15 lines of shell script.
这是包含三个图像的输出:
红色=80px宽
绿色=180 px 宽
蓝色=190px宽
这种方法对你有用吗?我可能可以在其他事情之间花一两天的时间来编写它!
这就是我的意思:
#!/bin/bash
# User-editable vertical spacing between images
SPACING=10
function centre() {
echo DEBUG: Centering $1
TEMP=$$tmp.png
w=$(convert "$1" -ping -format "%w" info:)
h=$(convert "$1" -ping -format "%h" info:)
convert -size ${MAXW}x${h} xc:"rgba(0,0,0,0)" PNG32:$TEMP
composite -resize '1x1<' -gravity center "$1" $TEMP $TEMP
if [ $2 -eq 0 ]; then
mv $TEMP output.png
else
convert output.png $TEMP -append output.png
rm $TEMP
fi
}
# Step 1 - determine widest image and save width in MAXW
MAXW=0
for i in *.jpg; do
w=$(convert "$i" -ping -format "%w" info:)
[[ $w -gt $MAXW ]] && MAXW=$w
echo DEBUG: Image $i width is $w
done
echo DEBUG: Widest image is $MAXW
# Step 2 - Create transparent spacer image, with width MAXW
convert -size ${MAXW}x${SPACING} xc:"rgba(0,0,0,0)" PNG32:spacer.png
# Step 3 - Build output image
n=0
for i in *.jpg; do
# Add a vertical spacer if not first image
[[ $n -ne 0 ]] && convert output.png spacer.png -append output.png
# Centre image horizontally and append to output
centre "$i" $n
((n++))
done
另一个完全不同的选项是添加 N 个图像的所有高度,并创建一个透明画布,其中最宽图像的宽度和所有图像的高度组合加上 (N-1)* 垂直间距。然后将图像叠加到画布上的正确位置 - 这涉及更多的数学运算和更少的图像处理和重新处理,这可能意味着这种方法损失的质量比我建议的方法要少。我会使用 PerlMagick 来实现这种方法,因为它比 bash 更适合数学。