2

我想让我的图像变成正方形而不影响它们的纵横比,所以我需要填充画布大小,例如使高度与宽度一样大,然后我可以重新缩放图像。我没有看到这样做的聪明方法。我查看了文档,但什么也没看到:http: //docs.wand-py.org/

似乎调整大小或作物不会这样做。我试过了:

img.crop(0, 0, width=dim, height=dim)

我很欣赏这个例程可能取决于背景,但如果我为了简单起见假设图像都具有白色背景(稍后我可能想要采样并添加背景类型)。

4

3 回答 3

3

如果您从命令行开始使用这样的图像:

convert -size 200x120 xc:red a.png

在此处输入图像描述

并将其调整为 100x100,如下所示:

convert a.png -resize 100x100 b.png

你会得到一个 100x60 的图像,因为 ImageMagick 想要保留长宽比。如果您希望将该图像填充到正方形,则需要-extent像这样使用(我已将背景设为黄色,以便您可以看到它):

convert a.png -resize 100x100 -background yellow -gravity center -extent 100x100 b.png

在此处输入图像描述

我在 Python Wand 文档中没有看到任何提及这个词-extent,所以我认为它不存在。因此,我认为您可能需要制作一个新的第二个方形图像并将调整大小的图像合成到它上面。除非其他人更了解...

于 2015-09-01T19:34:21.743 回答
1

Wand 提供变换,可以将图像缩放到所需的大小,同时保持纵横比。您可以用透明背景填充它,以使其稍后完全正方形。

def adjust_ratio(img, w_dst, h_dst):

    img.transform(resize="{0}x{1}".format(w_dst,h_dst))

    w_bor = (w_dst - self.img.width)/2
    h_bor = (h_dst - self.img.height)/2

    if w_bor>0:
        img.border(color=Color('transparent'),width=w_bor,height=0)
    else:
        img.border(color=Color('transparent'),width=0,height=h_bor)
于 2016-08-29T12:32:36.033 回答
0

使用来自评论的Luke的代码,我已经达到了预期的结果。

几乎没有改进,如果您还想为图像添加填充,您可以设置填充变量。

padding = 16
with Image(blob=png_image_blob) as foreground:
    foreground.transform(resize="{0}x{1}".format(width, height))
    with Image(width=width + padding, height=height + padding, background=Color('white')) as out:
        left = int((width - padding - foreground.size[0]) / 2) + padding
        top = int((height - padding - foreground.size[1]) / 2) + padding
        out.composite(foreground, left=left, top=top)
        out.save(filename=destination_file_path)
于 2018-08-06T16:37:00.667 回答