How to create thumbnails of images in Python
The PIL library
Python Imaging Library or PIL is an image processing library in python. This library supports a wide range of file formats, is designed for an efficient internal representation of image data, and provides powerful image processing capabilities.
The Image module
A class with the same name is provided by the Image module and is used to represent an image in PIL. The module also has factory functions, such as those for loading pictures from files and creating new images.
The thumbnail function
The thumbnail function is used to generate the thumbnail version of the given image no larger than itself. This method determines an acceptable thumbnail size to retain the image’s aspect ratio. This method modifies the image in-place, it modifies the original image. If the original image needs to be retained as is, then apply this function on the copy of the image.
Syntax
Image.thumbnail(size, resample=Resampling.BICUBIC)
Parameters
size: It is the size of the thumbnail.resample: It is the resampling filter. There are multiple filters inImage.Resamplingthat can be used.
Code example
Let’s look at the code below:
from PIL import Imageimport matplotlib.pyplot as pltimg = Image.open("educative.jpeg")SIZE = (75, 75)img.thumbnail(SIZE)img.save('educative_thumb.png')
Code explanation
- Line 1: We import the
Imagemodule fromPIL. - Line 3: We read
educative.jpeginto memory usingopen()inImagemodule. - Line 5: We define the size of the thumbnail.
- Line 7: We invoke the
thumbnail()method on the image object loaded in the Line 3. There is no return value as the operation is in-place. - Line 9: The thumbnail image is saved to disk.