Python:图像大小调整:保持比例 - 添加白色背景

Jay*_* D. 5 python image image-processing image-resizing

我想创建一个Python脚本来调整图像大小,但不是通过添加白色背景来改变其比例

(因此,a:500*700像素图像将通过在每侧添加100 px的白色条带转换为700*700像素图像)

我使用的三种图像类型是.PNG,.JPG和.GIF.我甚至不确定Gifs,PNG和JPG是否可能已经很棒了.

就我而言,他们必须是正方形.但是如果你们中的任何人设法做到适应任何比例的话,那么看到这个帖子的人数最多就会受益,你会更加棒极了!

我看到了其他语言的相同线程但不是python,你们知道你是怎么做到的吗?

PS:我使用的是Python 3

我尝试了什么:

将3张图像组合在一起.

如果我们拍摄500*700像素图像:创建两个100*700像素的白色图像,并在图像的每一侧放置一个.灵感来自:

使用Python水平组合多个图像

但是,我对python有点新意,我还没有成功.

est*_*evo 14

谢谢@Jay D.,这里有一个更通用的版本:

from PIL import Image

def resize(image_pil, width, height):
    '''
    Resize PIL image keeping ratio and using white background.
    '''
    ratio_w = width / image_pil.width
    ratio_h = height / image_pil.height
    if ratio_w < ratio_h:
        # It must be fixed by width
        resize_width = width
        resize_height = round(ratio_w * image_pil.height)
    else:
        # Fixed by height
        resize_width = round(ratio_h * image_pil.width)
        resize_height = height
    image_resize = image_pil.resize((resize_width, resize_height), Image.ANTIALIAS)
    background = Image.new('RGBA', (width, height), (255, 255, 255, 255))
    offset = (round((width - resize_width) / 2), round((height - resize_height) / 2))
    background.paste(image_resize, offset)
    return background.convert('RGB')
Run Code Online (Sandbox Code Playgroud)


Jay*_* D. 12

最后做到了:

def Reformat_Image(ImageFilePath):

    from PIL import Image
    image = Image.open(ImageFilePath, 'r')
    image_size = image.size
    width = image_size[0]
    height = image_size[1]

    if(width != height):
        bigside = width if width > height else height

        background = Image.new('RGBA', (bigside, bigside), (255, 255, 255, 255))
        offset = (int(round(((bigside - width) / 2), 0)), int(round(((bigside - height) / 2),0)))

        background.paste(image, offset)
        background.save('out.png')
        print("Image has been resized !")

    else:
        print("Image is already a square, it has not been resized !")
Run Code Online (Sandbox Code Playgroud)

感谢@Blotosmetek的建议,粘贴中心图像绝对比创建图像和组合它们更简单!

PS:如果你还没有PIL,用pip安装它的库的名字是"枕头",而不是PIL.但是,你仍然在代码中将它用作PIL.

  • 多谢,伙计。我也使用了您的解决方案。 (2认同)
  • 如果你想要透明而不是白色,请将 `(255, 255, 255, 255)` 更改为 `(0, 0, 0, 0)` (2认同)