Create thumbnail by resizing image in Python

Sometimes we need to create thumbnails of certain size from image. In this post I show you how to create thumbnail by resizing image in Python.
Here is the Python code for creating thumbnail / resizing an image:

import Image

def generate_and_save_thumbnail(imageFile, h, w, ext):
    image = Image.open(imageFile)
    image = image.resize((w, h), Image.ANTIALIAS)
    outFileLocation = "./images/"
    outFileName = "thumb"
    image.save(outFileLocation + outFileName + ext)

# set the image file name here
myImageFile = "myfile.jpg"
# set the image file extension
extension = ".jpg"
# set height
h = 200
# set width
w = 200

generate_and_save_thumbnail(myImageFile, h, w, extension)

The second argument of image.resize() is the filter. You have several options there:
  • Image.ANTIALIAS
  • Image.BICUBIC
  • Image.BILINEAR
  • Image.NEAREST

Each uses different algorithm. For downsampling (reducing the size) you can use ANTIALIAS. Other filers may increase the size.

You can also look at the following Python modules:

Comments

Unknown said…
Accepting height before width is just plain evil :)

Cheers for the code snippit
wingi said…
ANTIALIAS is for best quality and big cpu usage - saving image/file size can only triggerd by saving with lower quality setting.

Your example with ignore the aspect ratio of the source image ... look at united-coders.com for a more detailed example!

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code