Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

How to create thumbnails of images in Python

Ravi

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 in Image.Resampling that can be used.

Code example

Let’s look at the code below:

from PIL import Image
import matplotlib.pyplot as plt
img = Image.open("educative.jpeg")

SIZE = (75, 75)
  
img.thumbnail(SIZE)
  
img.save('educative_thumb.png')

Code explanation

  • Line 1: We import the Image module from PIL.
  • Line 3: We read educative.jpeg into memory using open() in Image module.
  • 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.

RELATED TAGS

python
RELATED COURSES

View all Courses

Keep Exploring