使用ImageMagick从文本生成图片?

4
我正在尝试使用ImageMagick创建3840 x 2160的缩略图。
我需要图片有黑色背景和白色文本。文本应该在垂直和水平方向上居中。
我想能够设置字体大小,但如果文本超出了图像范围,则自动减小字体大小以适应左右两侧的一定间距。
我将批量处理几十万张图片。从我所找到的信息来看,似乎必须始终设置字体大小,并且没有办法使其动态。
有人能否确认是否可以实现这个功能?
2个回答

8
你可以设置一个大小,指定文本可用的空间有多大,ImageMagick 将选择最大的点大小文本来适应它:
magick -gravity center -background black -fill white -size 400x300 -font /System/Library/Fonts/MarkerFelt.ttc    caption:"Short Text" short.png

enter image description here

magick -gravity center -background black -fill white -size 400x300 -font /System/Library/Fonts/MarkerFelt.ttc    caption:"Somewhat longer text that will get rendered in a smaller font" long.png

enter image description here


如果您想要文字周围有边距,您可以设置文本的最大尺寸,然后使用-extent增加画布的大小 - 我将以红色执行此操作,以便您可以看到-extent添加了什么:
magick -gravity center -background black -fill white -size 400x300 -font /System/Library/Fonts/MarkerFelt.ttc    caption:"Somewhat longer text" -background red -extent 410x400 long.png

enter image description here


如果您正在从文件中读取行来生成成千上万的图像,则可以通过以下方式从另一个命令中输入文本:

echo -n "Text supplied by other command" | magick -gravity center -background black -fill white -size 400x300 -font /System/Library/Fonts/MarkerFelt.ttc caption:@- result.png 

enter image description here


如果您想知道ImageMagick选择了什么点大小,您可以按照以下方式获取:

magick identify -format "%[caption:pointsize]\n" result.png
59

如果你使用的是 macOS 或 Linux,你可以使用 GNU Parallel 快速处理数十万张图片。如果你对此感兴趣,请联系我。 - Mark Setchell

1
我使用以下脚本生成基于文本的缩略图,所有我最喜欢的ttf字体文件都在之前复制到同一个文件夹中:
ls -1 *.ttf | while read line
do
magick -gravity center -background '#086cdf' -fill '#f1fffe' -size 490x400 -font "$line" caption:"Sample Text" -background red -extent 500x500 "$(echo "$line"|sed 's/.ttf/_icon.png/')"
done

上述脚本生成大小为500x500像素的图标缩略图。

对于像YouTube这样的社交媒体平台,缩略图必须是1280x720的尺寸,我使用以下脚本来生成它:

ls -1 *.ttf | while read line
do
magick -gravity center -background '#086cdf' -fill '#f1fffe' -size 1270x620 -font "$line" caption:"Sample Text" -background red -extent 1280x720 "$(echo "$line"|sed 's/.ttf/_Social_Media_Platforms.png/')"
done

希望这些脚本能够帮助那些正在寻找解决方案的人。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接