如何让 PIL 在创建缩略图时考虑最短边?
目前,对于我的下面的功能...图像将根据最长边调整大小。
基本上图像的高度较大,高度为 200px。宽度将只是...无论如何...
如果图像具有较大的宽度,则宽度将为 200px,并且高度将相应调整。
我该如何扭转这个局面!?我希望这个函数考虑到最短边。
我这个函数写错了吗?
def create_thumbnail(f, width=200, height=None, pad = False):
#resizes the longest side!!! doesn't even care about the shortest side
#this function maintains aspect ratio.
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:
pass
#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
Currently, for my function below...the image will be resized based on the longest side.
Basically the image has a larger height, the height will be 200px. The width will be just...whatever...
If the image has a larger width, the width will be 200px, and the height will adjust accordingly.
How do I flip this around!? I want this function to take into account the shortest side.
Am I writing this function incorrectly??
def create_thumbnail(f, width=200, height=None, pad = False):
#resizes the longest side!!! doesn't even care about the shortest side
#this function maintains aspect ratio.
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:
pass
#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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
调整大小
而不是缩略图
。缩略图背后的要点是可以轻松地缩小图像以适应特定的边界框,并保持纵横比。这意味着如果您的边界框是正方形,则图像的较长边决定所使用的比例。
resize
为您提供更直接的控制 - 您可以准确指定所需的大小。实际上,由于您想保留方面,您仍然可以使用缩略图,但您需要捏造边界框。在调用
thumbnail
之前,请尝试执行以下操作:Use
resize
instead ofthumbnail
.The point behind
thumbnail
is to make it easy to scale an image down to fit within a particular bounding box preserving aspect ratio. That means that if your bounding box is a square, the longer side of the image determines the scale used.resize
gives you more direct control -- you specify exactly what size you want.Actually, since you want to preserve aspect you could still use thumbnail, but you need to fudge the bounding box. Before your call to
thumbnail
, try doing this:我不久前将这个函数放在一起:
它将图像的大小调整为最大尺寸,并保留其最长的尺寸并保留纵横比
i put together this function a while ago:
it resizes an image down to at most size on its longest size preserving aspect ratio