我想创建一个 Python 脚本来调整图像大小,但不改变其比例,只需添加白色背景即可
(因此,通过在每侧添加 100 像素的白色带,500*700 像素的图像将转换为 700*700 像素的图像)
我使用的三种图像类型是 .PNG、.JPG 和 .GIF。我什至不确定 Gif、PNG 和 JPG 是否已经很棒了。
在我的例子中,它们必须是正方形。但是如果你们中的任何一个人设法适应任何比例,这将有利于看到这个帖子的最大数量的人,你会更棒!
我看到了其他语言的相同线程,但不是 python,你们知道你们是怎么做到的吗?
附言:我正在使用 Python 3
我尝试了什么:
将 3 张图像组合在一起。
如果我们拍摄 500*700 像素的图片: 创建两个 100*700px 的白色图像,并在图像的每一侧放置一个。灵感来自:
Combine several images horizontally with Python
但是,我是 python 的新手,我还没有成功。
最佳答案
终于做到了:
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 安装它的库名称是“pillow”,而不是 PIL。但是,您仍然在代码中将其用作 PIL。
关于Python:调整图像大小:保持比例 - 添加白色背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44370469/