Python: Image resizing: keep proportion - add white background

前端 未结 3 939
误落风尘
误落风尘 2021-01-02 16:50

I would like to create a Python script to resize images, but not changing its proportions, just by adding a white background

(So, a : 500*700 px im

3条回答
  •  被撕碎了的回忆
    2021-01-02 17:47

    Finally did it :

    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 !")
    

    Thanks to @Blotosmetek for the suggestion, pasting a centered image is definitely simpler than creating images and combining them !

    PS : If you don't have PIL yet, the library's name to install it with pip is "pillow", not PIL. But still, you use it as PIL in the code.

提交回复
热议问题