Python Pillow - Creating Thumbnails



Sometimes, it is required to have all images of equal height and width. One way to achieve this, is by creating a thumbnail of all images using the thumbnail() function from pillow library.

This method modifies the image to contain a thumbnail version of itself and the size of the image will be no larger than the given size.

The method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the draft () method to configure the file reader (where applicable) and finally, resizes the image.

Syntax

Image.thumbnail(size, resample=3)

Where,

  • Size − Required size

  • Resample − Optional resampling filter. It can be one of these PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC, or PIL.Image.LANCZOS. If omitted, it defaults to PIL.Image.BICUBIC.

  • Returns − None

Example

Following example demonstrates the creation of a thumbnail using python pillow −

from PIL import Image
def tnails():
   try:
      image = Image.open('images/cat.jpg')
      image.thumbnail((90,90))
      image.save('images/thumbnail.jpg')
      image1 = Image.open('images/thumbnail.jpg')
      image1.show()
   except IOError:
      pass
tnails()

Output

If you save the above program as Example.py and execute, it displays the created thumbnail using the default PNG display utility, as follows −

Original image

original_image.jpg

Output image

Output Image
Advertisements