【问题标题】:Pad image with transparency so it is sized as multiplies of 300 in both directions (ImageMagick 7)用透明度填充图像,使其在两个方向上用作 300 的倍数(ImageMagick 7)
【发布时间】:2026-01-17 14:15:02
【问题描述】:

我的问题有点类似于这个问题:How to square an image and pad with transparency from the commandline (imagemagick),但我不想对图像进行平方,只将其向上缩放到每个方向上最近的 300 倍数,并用透明度填充。原始图像应在此新填充内居中。

例子:

输入图像:宽 1004 像素,高 250 像素 输出图片:宽1200px,高300px,原图居中。

如果这很重要,我正在尝试使用 Mac 终端来实现这一点。

我已经设法在上面的链接中进行了转换,以及其他必要的转换列表,但是我很难使用提供的 IM 变量以及用于舍入浮点数的数学函数,以及一个 distort:viewport 功能,这似乎是我应该使用的功能?

【问题讨论】:

    标签: imagemagick imagemagick-convert


    【解决方案1】:

    我想你想要这个:

    magick -gravity center start.png -background yellow -extent "%[fx:int((w+299)/300)*300]x%[fx:int((h+299)/300)*300]" result.png
    

    所以,如果我们从您的 1004x250 尺寸开始:

    你会得到这个:

    显然,您希望将 yellow 替换为 none 以获得透明边框,但我希望在 * 上可见范围。

    如果您使用不同的倍数,我的公式中的299 就是multiple - 1。所以,你可以把答案改成这样:

    MULT=300
    magick -gravity center start.png -background yellow -extent "%[fx:int((w+$MULT-1)/$MULT)*$MULT]x%[fx:int((h+$MULT-1)/$MULT)*$MULT]" result.png
    

    或者,如果您不喜欢丑陋的 %[fx:...] 表达式,您可以在 shell 中完成所有数学运算:

    # Establish the multiple
    MULT=300
    # Get existing image width and height
    read w h < <(magick -format "%w %h" start.png info:)
    # Calculate new width and new height
    ((NW=((w+MULT-1)/MULT)*MULT))
    ((NH=((h+MULT-1)/MULT)*MULT))
    magick -gravity center start.png -background yellow -extent "$NWx$NH" result.png
    

    【讨论】:

    • 太好了,非常感谢,这就像一个魅力!感谢 %[fx:... 东西中的额外“解决方法”,在我看来,这些东西使用起来非常令人困惑。
    • 酷 - 很高兴它对你有用。祝你的项目好运!