简体   繁体   中英

Resizing an image in PIL

I have the following function which takes an image and then returns it in three sizes. Another function then uploads those images to Amazon S3. It seems to me like there is some redundancy in how the file is being saved -

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)

Is there a way to improve this?

You could replace:

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

with

image.thumbnail(size_as_tuple, Image.ANTIALIAS)

(especially since width and height are swapped; it should be width, height = size_as_tuple )

And you don't need the open() . image.save(os.path.join('/tmp', filename)) is enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM