开发者

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

开发者 https://www.devze.com 2023-01-28 10:38 出处:网络
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.

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. But I want to resize it to 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.

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.

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开发者_如何学C
    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.


One option is to create a blank white image of the size you want, then draw the existing image in the center.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号