Python 中的图像创建和字体

Image creation and fonts in Python

我使用 PIL 在 python 中创建了一组图像。除此之外,我还实现了 textwrap 以便将文本放在我创建的图像上,但是,它们并不十分完美。首先,下面是我创建的三个图像示例。

这三张图片的宽度不同,但我希望它们都具有相同的宽度,而高度不是问题,可以比彼此高或低;宽度是唯一必须保持一致的东西。除此之外,我还使用了 utf-8 编码以便在图像上获取此文本,但我希望字体看起来更像以下内容

上图中还显示了这些盒子的堆叠方式——这就是我想要的最终产品的方式。而不是三个单独的带边框文本图像,我想要一个包含那些带边框文本框的图像。这是我当前输出的代码

for match in find_matches(text=fullText):
ct += 1
match_words = match.split(" ")
match = " ".join(match_words[:-1])
print(match)
W, H = 300, 300
base = Image.new("RGB", (W, H), (255, 255, 255))
draw = ImageDraw.Draw(base)
font = ImageFont.load_default()

current_h, pad = 50, 5

for key in textwrap.wrap(match, width=50):
    line = key.encode("ascii")
    w, h = draw.textsize(line, font=font)
    draw.text(((W - w) / 2, current_h), line, (0, 0, 0), font=font)
    current_h += h + pad
draw.text((W / 2, current_h), str(ct).encode("utf-8"), (0, 0, 0), font=font)
for count, matches in enumerate(match):
    base.save(f"{ct}C.png")
    bbox = ImageOps.invert(base).getbbox()
    trim = base.crop(bbox)
    patent = ImageOps.expand(trim, border=5, fill=(255, 255, 255))
    patent = ImageOps.expand(patent, border=3, fill=(0, 0, 0))
    patent.save(f"{ct}C.png")
    p_w, p_h = patent.size
    Image.open(result_fpath, "r")
    result.paste(patent)
    result.save(result_fpath)

最后,这必须是一个自动化过程。我在想可以将堆叠的盒子变成单个图像的方法是一个 for 循环,它接收创建的图像,然后将它们粘贴到与第一个粘贴图像大小相同的图像中,该图像会为每个后续图像适当调整大小带边框的文本框。如果能提供任何帮助,我将不胜感激。

我发现使用 ImageMagick 这类事情要容易得多,wand.

提供了不错的绑定

以下是制作一张图片的方法,只需在终端的 command-line 处,以不同颜色显示各个部分,以便您了解哪些因素会影响哪些因素:

magick -background yellow -gravity center -pointsize 24 -size 400x caption:"Detecting, by the component, that a replacement component has been added in the transport\n246C" -bordercolor magenta -border 10 -bordercolor cyan -border 5 result.png

下面是您可以一次性完成几项的方法:

magick -background white -gravity center -pointsize 24 -size 400x -bordercolor black \
 \( caption:"Detecting, by the component, that a replacement component has been added in the transport\n246C" -bordercolor black -border 5 -bordercolor white -border 5 \) \
 \( caption:"Detecting, by the component, that another component has been removed\n246D" -bordercolor black -border 5 -bordercolor white -border 5  \)  \
 \( caption:"Detecting, by any means, that another component has been replaced\n247K" -bordercolor black -border 5 -bordercolor white -border 5 \)  \
 -append result.png

当然,您可以更改字体、更改颜色、从文件中读取标题、使用 Unicode,space 以不同的方式 and/or 在 Python 中完成这一切,非常 similar-looking 代码 - here 是一个 link 的答案,显示 Python.[= 中 wand 中的近似技术。 17=]