我有一个与此非常相似的问题: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))
但这不起作用,因为它仍然会将一些图像拉伸(stretch)成方形(至少是示例中的图像 b。对于大图像来说,它似乎会旋转它们!
请您参考如下方法:
问题出在你对图片大小的计算不正确:
w = max(desired_w, x)
h = max(desired_h, y)
您只是独立地获取最大尺寸 - 而没有考虑图像的纵横比。想象一下,如果您的输入是一张 1000x1000 的正方形图像。您最终会创建一个黑色的 1000x1000 图像,将原始图像粘贴到它上面,然后将其大小调整为 244x138。要获得正确的结果,您必须创建 1768x1000 图像而不是 1000x1000 图像。
这是考虑了纵横比的更新代码:
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
ratio = x / y
desired_ratio = desired_w / desired_h
w = max(desired_w, x)
h = int(w / desired_ratio)
if h < y:
h = y
w = int(h * desired_ratio)
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))
