1

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

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

4

2 回答 2

4

我不确定您的要求是什么,但我猜您想在图像“下方”写一个标签。库的示例。

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):

创建两个图像。您将负责logo:用您的 ByteIO 缓冲区替换图像。该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:

创建第三个“空白”图像,该图像足够大以包含两个图像。

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

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

于 2018-03-27T21:29:14.973 回答
0

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

考虑一些更便携和包含的东西,比如 Pillow,它有很多功能可以实现你的目标。

pip install 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/

于 2018-03-27T17:21:46.090 回答