在PIL中调整图像大小

时间:2012-05-21 07:26:22

标签: python python-imaging-library

我有以下功能拍摄图像,然后以三种尺寸返回。然后,另一个功能将这些图像上传到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)

有没有办法改善这个?

1 个答案:

答案 0 :(得分:2)

您可以替换:

height, width = size_as_tuple[0], size_as_tuple[1]
image.thumbnail((height, width), Image.ANTIALIAS)

image.thumbnail(size_as_tuple, Image.ANTIALIAS)

(特别是自widthheight交换后;应为width, height = size_as_tuple

而且您不需要open()image.save(os.path.join('/tmp', filename))就足够了。