Python Pillow creates thumbnails

Creating Thumbnails with Python Pillow

Sometimes, you want all your images to have the same height and width. One way to achieve this is to use the thumbnail() function in the pillow library to create thumbnails for all your images.

This method modifies the image so that it contains a thumbnail version of itself, and the image size will not be larger than the given dimensions.

This method calculates an appropriate thumbnail size to preserve the image’s height and width, calls the draft() method to configure the profile reader (if applicable), and finally, resizes the image.

Syntax

Image.thumbnail(size, resample=3)

Where?

  • size – The desired size
  • Resample – The optional resampling filter. This can be one of PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC, or PIL.Image.LANCZOS. If omitted, it defaults to PIL.Image.BICUBIC.

  • Returns – None

Example

The following example demonstrates creating a thumbnail using 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, it will display the created thumbnail using the default PNG display tool, as shown below.

Original Image

Python Pillow - Create Thumbnail

Output Image

Python Pillow - Create Thumbnail

Leave a Reply

Your email address will not be published. Required fields are marked *