如何修改 Python 图像调整器代码来实现此目的?
当我调整小于所需的图片大小时,我希望图像不被调整大小......而是位于中心,周围有白色填充。
假设我有一个 50x50 的图标。但我想将其大小调整为 100x100。如果我将它传递给此函数,我希望它返回相同的居中图标,每侧填充 25 像素的白色填充。
当然,我希望它能够处理任何宽度/高度的图像,而不仅仅是像上面的示例那样的正方形。
我当前的代码如下。
我不知道为什么我这样做 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
这段代码可能有很多错误,不确定。
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
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种选择是创建所需尺寸的空白白色图像,然后在中心绘制现有图像。
One option is to create a blank white image of the size you want, then draw the existing image in the center.