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 heremyImageFile = "myfile.jpg"# set the image file extensionextension = ".jpg"# set heighth = 200# set widthw = 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:
  1. imageop
  2. imghdr

Comments

Popular Posts