使用 ImageMagick 转换附加图像

问题描述 投票:0回答:3

所以我有一堆图像想要垂直附加:

convert *.png -append output.png

但是我遇到了两个问题:

  1. 并非所有图像的宽度都相同。因此,宽度小于最宽图像的图像后面有空白,因为它们是左对齐的。
  2. 图像之间没有间距。

如何居中对齐所有图像并指定它们之间的间距?

graphics bitmap imagemagick imagemagick-convert
3个回答
9
投票

只需使用 ImageMagick 的 montage 实用程序。使用 -gravity-extent 选项对齐图像,并使用 -geometry 调整间距。

montage fishscales.png circles.png verticalsaw.png \
        -tile 1x -geometry +10+10 \
        -gravity Center -extent 120 \
        out.png

montage example


2
投票

我的方法是使用 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宽

enter image description here

这种方法对你有用吗?我可能可以在其他事情之间花一两天的时间来编写它!

这就是我的意思:

#!/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 更适合数学。


0
投票

ImageMagick 有一个

-smush
选项,可以与
-gravity
结合使用,将不同宽度的图像连接在一起并根据需要对齐。

这将获取当前文件夹中的所有

.png
文件,并将它们集中在一个大
.png
中,每个图像之间有 17 像素的间隙,较小的图像具有绿色背景:

convert -smush 17 -gravity center -background green *.png everything.png

如果您想从左到右连接文件,请使用

+smush

© www.soinside.com 2019 - 2024. All rights reserved.