Python3: Resize rectangular image to a different kind of rectangle, keeping ratio and fill background with black
我有一个非常类似的问题:将矩形图像调整为正方形,保持比例,并用黑色填充背景,但是我想将其调整为非正方形图像,并在需要时将图像水平或垂直居中。
以下是所需输出的一些示例。 我完全使用Paint制作了这张图片,因此这些图片实际上可能无法完美居中,但是居中是我想要实现的目标:
我尝试了从链接的问题中编辑的以下代码:
1 2 3 4 5 6 7 8 9 10 | 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。对于大图像,似乎是旋转它们了!)
问题在于您对图像尺寸的错误计算:
1 2 | w = max(desired_w, x) h = max(desired_h, y) |
您只需要独立考虑最大尺寸-无需考虑图像的长宽比。 想象一下,如果您的输入是1000x1000的方形图像。 您最终将创建一个黑色的1000x1000图像,将原始图像粘贴在其上,然后将其调整为244x138。 为了获得正确的结果,您将必须创建1768x1000的图像,而不是1000x1000的图像。
这是考虑长宽比的更新代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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)) |