无法使用 ImageMagick 使文本适合图像

Can't fit text to image with ImageMagick

我需要使文字适合图像。我的图像有不同的尺寸,所以我不能设置恒定的点数。

我的命令看起来像这样

convert 
    -fill white
    -font Winter Calligraphy
    -size `${options.width}x${options.height}`
    label: KJHGFD
    test.gif

在输出时,您可以在图片顶部看到裁剪部分。

输出:

这对我适用于 ImageMagick 6.9.10.97 Q16 Mac OSX。我已将 -background white -fill black -gravity center 添加到您的命令中。

convert -background white -fill black -font "/library/fonts/Winter Calligraphy.ttf" -size 569x196 -gravity center label:KJHGFD test.gif


这里有一个稍微笨拙的方法来获得你想要的结果。以下是步骤:

  • 首先,使用 caption: 获取 ImageMagick 以告诉您它将用于填充文本框并提取该信息的磅值

  • 创建一个 canvas 两倍于你真正想要的那个的宽度和两倍的高度,然后在中间绘制你的文本 - 它一定会适合!

  • 现在 trim 去除文本周围的无关背景,这样您就有了包含文本的绝对最小边界框

  • 将结果调整为您想要的大小。


#!/bin/bash

# Width, height and text
w=600
h=150
text="KJHGFD"

# Get pointsize ImageMagick thinks is good
pointsize=$(convert -gravity center -background black -fill white -size ${w}x${h} \
    -font "Winter Calligraphy.ttf" caption:"$text" -format "%[caption:pointsize]" info:)

echo ImageMagick likes pointsize: $pointsize

# So draw text in that size on larger canvas, trim to bounds of letters and resize to desired size
wb=$((w*2))
hb=$((h*2))
convert -gravity center -fill white -size ${wb}x${hb} xc:black \
    -font "Winter Calligraphy.ttf" -pointsize $pointsize -annotate 0 "$text" \
    -trim +repage -resize ${w}x${h}\! result.png