Python: Resize an image and keep aspect ratio

A handy little snippet that saves you a lot of work is the ability to quickly generate thumbnails from a source image.

from PIL import Image

filename = "/tmp/thumbnail_file.jpg"

# Read the image, resize and save as a temporary file
image = Image.open(input_filename)

image.thumbnail([max_width, max_height], Image.ANTIALIAS)

image.save(filename, "JPEG")

Image.ANTIALIAS option is the best for sizing down. See the docs for other resize filters.

One thing to keep in mind is that Image.resize() actually resizes the whole image to fit the given size exactly, without preserving the aspect ratio.

toddler_air_hump
Proceed to bust a move!

Source

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog