【发布时间】:2018-09-25 12:14:11
【问题描述】:
我有一个与此非常相似的问题:Resize rectangular image to square, keeping ratio and fill background with black,但我想调整为非方形图像的大小,并在需要时将图像水平或垂直居中。
以下是一些所需输出的示例。我完全用 Paint 制作了这张图片,所以图片实际上可能不是完全居中的,但居中是我想要实现的:
我尝试了从链接的问题中编辑的以下代码:
def fix_size(fn, desired_w=256, desired_h=256, fill_color=(0, 0, 0, 255)):
"""Edited from https://stackoverflow.com/questions/44231209/resize-rectangular-image-to-square-keeping-ratio-and-fill-background-with-black"""
im = Image.open(fn)
x, y = im.size
#size = max(min_size, x, y)
w = max(desired_w, x)
h = max(desired_h, y)
new_im = Image.new('RGBA', (w, h), fill_color)
new_im.paste(im, ((w - x) // 2, (h - y) // 2))
return new_im.resize((desired_w, desired_h))
但这不起作用,因为它仍然会将一些图像拉伸成方形(至少是示例中的图像 b。对于大图像,它似乎会旋转它们!
【问题讨论】:
标签: python python-3.x image