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.thumbnail([max_width, max_height], Image.ANTIALIAS), "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.

Proceed to bust a move!


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