我正在尝试使用 ImageMagick 创建 3840 x 2160 的缩略图。
我需要图像具有黑色背景和白色文本。 文本应垂直和水平居中。
我希望能够设置字体大小,但如果文本超出图像,则会自动减小字体大小,使其适合左侧和右侧的一定量的填充。
我将使用数十万张图像批量进行此操作。 从我发现的情况来看,您似乎总是必须设置字体大小,并且无法使其动态。
有人可以确认这是否可行吗?
您可以设置一个大小来指定文本的可用空间有多大,ImageMagick将选择适合的最大磅值文本:
magick -gravity center -background black -fill white -size 400x300 -font /System/Library/Fonts/MarkerFelt.ttc caption:"Short Text" short.png
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
如果您想要文本周围有边距,您可以设置文本的最大尺寸,然后使用
-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
如果您正在从文件中读取行以生成数十万张图像,则可以从另一个命令中输入文本,如下所示:
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
如果你想知道ImageMagick选择了什么pointsize,你可以这样得到:
magick identify -format "%[caption:pointsize]\n" result.png
59
我使用以下脚本生成基于文本的缩略图,其中包含所有我最喜欢的 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
希望所有这些脚本可以帮助人们在谷歌上搜索解决方案。
也许有人会发现通过 Python 脚本运行图像生成很有用。
最简单的方法是使用
invoke
库来传递您在终端中输入的命令。
from invoke import run
run('convert -gravity center -background black -fill white -size 200x200 caption:"qwerty" -background black -extent 400x400 qwerty.png')
或使用
Image
中的 wand
。
from wand.image import Image
with Image(width=200, height=200, pseudo=f'caption:qwerty') as img:
img.save(filename='qwerty.png')