用Python和MagickWand创建方形缩略图

0 投票
2 回答
769 浏览
提问于 2025-04-18 12:48

我想知道怎么用Python和Wand库制作正方形的缩略图。我想从任何大小的源图片中生成正方形的缩略图。重要的是,缩略图要和原图保持相同的比例,裁剪是可以的,而且缩略图要填满整个空间。

2 个回答

1

这里有几个要点:

  • 不裁剪。
  • 用颜色填充空白区域(在这个例子中是:白色)。
  • 保持宽高比。
from math import ceil
from wand.image import Color


def square_image(img):
    width = float(img.width)
    height = float(img.height)
    if width == height:
        return img
    border_height = 0
    border_width = 0
    if width > height:
        crop_size = int(width)
        border_height = int(ceil((width - height)/2))
    else:
        crop_size = int(height)
        border_width = int(ceil((height - width)/2))
    img.border(color=Color('white'), height=border_height, width=border_width)
    img.crop(top=0, left=0, width=crop_size, height=crop_size)
    return img
2

下面这个 crop_center() 函数可以把给定的图片变成正方形。

from __future__ import division

from wand.image import Image


def crop_center(image):
    dst_landscape = 1 > image.width / image.height
    wh = image.width if dst_landscape else image.height
    image.crop(
        left=int((image.width - wh) / 2),
        top=int((image.height - wh) / 2),
        width=int(wh),
        height=int(wh)
    )

首先,你需要把图片处理成正方形,然后你可以用 resize() 方法把这个正方形缩小。

撰写回答