简体   繁体   English

如何修改我的Python图像缩放器代码以执行此操作?

[英]How do I modify my Python image resizer code to do this?

When I resize a picture that is smaller than desired, I want the image to NOT get resized...but instead be in the center, with white padding around it. 当我调整尺寸小于所需大小的图片时,我不希望图像重新调整大小,而是要居中,并在其周围使用白色填充。

So, let's say I have an icon that's 50x50. 因此,假设我有一个50x50的图标。 But I want to resize it to 100x100. 但我想将其尺寸调整为100x100。 If I pass it to this function, I would like it to return me the same icon that is centered, with white padding 25 pixels on each side. 如果将其传递给此函数,我希望它返回给我相同的图标,该图标居中,并且每边白色填充25像素。

Of course, I'd like this to work with images of any width/height, and not just a square like the example above. 当然,我希望它可以处理任何宽度/高度的图像,而不仅仅是上面示例中的正方形。

My current code is below. 我当前的代码如下。

I don't know why I did if height=None: height=width ...I think it was just because it worked when I did it before. 我不知道为什么if height=None: height=width ...我做那只是因为它在我之前做过才起作用。

def create_thumbnail(f, width=200, height=None):
    if height==None: height=width
    im = Image.open(StringIO(f))
    imagex = int(im.size[0])
    imagey = int(im.size[1])
    if imagex < width or imagey < height:
        return None
    if im.mode not in ('L', 'RGB', 'RGBA'):
        im = im.convert('RGB')
    im.thumbnail((width, height), Image.ANTIALIAS)
    thumbnail_file = StringIO()
    im.save(thumbnail_file, 'JPEG')
    thumbnail_file.seek(0)
    return thumbnail_file

This code may have many bugs in it, not sure. 不确定,此代码中可能包含许多错误。

一种选择是创建所需大小的空白白色图像,然后在中心绘制现有图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM