最后做到了:
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的建议,粘贴中心图像绝对比创建图像和组合它们更简单!
PS:如果你还没有PIL,用pip安装它的库的名字是“枕头”,而不是PIL.但是,你仍然在代码中将它用作PIL.