且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2021-10-23 09:38:42

最后做到了:

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

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

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

PS:如果您还没有PIL,则要通过pip安装它的库名称是枕头",而不是PIL.但是,您仍然可以在代码中将其用作PIL.

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.