使用 python 和 imagemagick 添加图像

Appending images using python and imagemagick

关于 python 的 imagemagick,大多数人推荐 "wand",但我如何在 python 中使用它附加图像?我想在 python 中使用 imagemagick 将标签添加到图像底部:http://www.imagemagick.org/Usage/annotating/ 但魔杖 api 似乎非常基本并且没有很多 imgemagick 命令,包括标签和附加。

在 python 中还有其他使用 imagemagick 的方法吗?我的图像是 png 类型,并且是 python 代码中的 BytesIO 流而不是文件,因此我无法使用命令行将它们传递给 imagemagick,也无法将它们保存在任何临时文件中。

Imagemagick 很棒,但学习曲线陡峭。您需要安装第 3 方 ImageMagick(必须是 32 位或 64 位,具体取决于您的 python 版本)。考虑到您需要将其添加到路径并且可执行文件对于 运行 您的脚本是必需的,单独安装是一件很痛苦的事情。

考虑一些更便携和包含的东西,比如 Pillow,它具有实现您的目标的许多功能。

pip install pillow

在 pillow 中,您可以从 BytesIO 读取图像。并在上面画画或打印。有许多可用的选项。

from PIL import Image, ImageDraw
import io


# Reading bytes from file but you can skip that and simply open your bytes like below.

with open('picture.jpg', 'rb') as f:
    im = Image.open(io.BytesIO(f.read()))
    draw = ImageDraw.Draw(im)
    draw.text((10,10), "Hello World", fill=(255))
    im.show() # do whatever you like with the image

查看文档以获取更多示例。 https://pillow.readthedocs.io/en/latest/

我不太确定你要什么,但我猜你想写一个标签 "below" 一张图片。这是 库的示例。

from wand.image import Image
from wand.compat import nested
from wand.color import Color
from wand.font import Font

with nested(Image(filename='logo:'),
            Image(filename='null:')) as (source, text):
    text.font = Font('Impact', 64)
    text.read(filename='label:Hello world!')
    largest_width = max(source.width, text.width)
    offset = (largest_width - min(source.width, text.width)) / 2
    with Image(width=largest_width,
               height=source.height + text.height,
               background=Color('WHITE')) as dst:
        dst.composite(source, 0, 0)
        dst.composite(text, int(offset), source.height)
        dst.save(filename="output.png")

概览

with nested(Image(filename='logo:'),
            Image(filename='null:')) as (source, text):

创建两个图像。您将负责用您的 ByteIO 缓冲区替换 logo: 图像。 null: 图像是分配魔杖实例的占位符。

    text.font = Font('Impact', 64)
    text.read(filename='label:Hello world!')

这定义了要绘制的字体和文本。 label: 协议可以替换为 caption: 以获得其他行为(?)。

    with Image(width=largest_width,
               height=source.height + text.height,
               background=Color('WHITE')) as dst:

创建第三张 "blank" 大到足以包含两张图片的图片。

        dst.composite(source, 0, 0)
        dst.composite(text, int(offset), source.height)

将图像数据从 source & text 复制到新图像。