Python:图像调整大小:保持比例-添加白色背景 [英] Python: Image resizing: keep proportion - add white background

查看:750
本文介绍了Python:图像调整大小:保持比例-添加白色背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

(So, a : 500*700 px image would transform to a 700*700 px image by adding 100 px of a white band on each side)

我使用的三种图像类型是.PNG,.JPG和.GIF .我什至不知道Gif,PNG和JPG的功能是否可能已经很棒.

The three image types I use are .PNG, .JPG and .GIF. I am not even sure it is possible for Gifs, PNG and JPG would already be awesome.

在我的情况下,它们必须是正方形.但是,如果你们中的任何一个设法适应任何比例,都会使看到此线索的最大人数受益,您将变得更棒了!

In my case, they have to be squares. But if any of you manage to do it for adaptable to any proportion, it would benefit the maximum number of people that see this thread and you would be even more awesome !

我在其他语言中看到了相同的线程,但没有看到python,你们知道如何做到这一点吗?

I saw same threads for other languages but not python, do you guys know how you do this ?

PS:我正在使用Python 3

PS : I am using Python 3

我尝试过的事情:

将3张图像组合在一起.

Combining 3 images together.

如果我们拍摄500 * 700像素的图片: 创建两个100 * 700px的白色图像,并在图像的每一侧放置一个.受启发:

If we take our 500*700 px image : Creating two white images of 100*700px and put one on each side of the image. Inspired by :

使用Python水平合并几张图像

但是,我是python的新手,但没有成功.

But, I am kind of new on python, and I haven't succeded.

推荐答案

最后做到了:

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.

这篇关于Python:图像调整大小:保持比例-添加白色背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆