[英]Resizing an image in PIL
我有以下功能,它采取圖像,然后以三種尺寸返回它。 然后,另一個功能將這些圖像上傳到Amazon S3。 在我看來,文件如何保存有一些冗余 -
def resize_image(image, size_as_tuple):
"""
Example usage: resize_image(image, (100,200))
"""
image_as_string=""
for c in image.chunks():
image_as_string += c
imagefile = cStringIO.StringIO(image_as_string)
image = Image.open(imagefile)
if image.mode not in ("L", "RBG"):
image = image.convert("RGB")
filename = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(14)) + ".jpg"
height, width = size_as_tuple[0], size_as_tuple[1]
image.thumbnail((height, width), Image.ANTIALIAS)
imagefile = open(os.path.join('/tmp', filename), 'w')
image.save(imagefile, 'JPEG')
imagefile = open(os.path.join('/tmp', filename), 'r')
content = File(imagefile)
return (filename, content)
有沒有辦法改善這個?
你可以替換:
height, width = size_as_tuple[0], size_as_tuple[1]
image.thumbnail((height, width), Image.ANTIALIAS)
同
image.thumbnail(size_as_tuple, Image.ANTIALIAS)
(特別是因為交換了width
和height
;它應該是width, height = size_as_tuple
)
而且你不需要open()
。 image.save(os.path.join('/tmp', filename))
就足夠了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.