”;
Thumbnails, smaller and compressed versions of original images, serve as essential components in various applications, including image previews, web development, and optimizing the loading speed of web pages and applications with heavy images.
In this tutorial, we”ll explore using Matplotlib to efficiently generate image thumbnails. Matplotlib takes the support of the Python Pillow library for image processing and allows us to easily generate thumbnails from existing images.
Image thumbnail in Matplotlib
Matplotlib offers the thumbnail() function within its image module to generate thumbnails with customizable parameters, allowing users to efficiently create scaled-down versions of images for various purposes.
Following is the syntax of the function −
Syntax
matplotlib.image.thumbnail(infile, thumbfile, scale=0.1, interpolation=''bilinear'', preview=False)
Here are the details of its parameters −
-
infile − The input image file. As you know that Matplotlib relies on Pillow for image reading, so it supports a wide range of file formats, including PNG, JPG, TIFF, and others.
-
thumbfile − The filename or file-like object where the thumbnail will be saved.
-
scale − The scale factor for the thumbnail. It determines the size reduction of the thumbnail relative to the original image. A smaller scale factor generates a smaller thumbnail.
-
interpolation − The interpolation scheme used in the resampling process. This parameter specifies the method used to estimate pixel values in the thumbnail.
-
preview − If set to True, the default backend (presumably a user interface backend) will be used, which may raise a figure if show() is called. If set to False, the figure is created using FigureCanvasBase, and the drawing backend is selected as Figure.savefig would normally do.
The function returns a Figure instance containing the thumbnail. This Figure object can be further manipulated or saved as needed.
Generating Thumbnails for a single image
Matplotlib supports various image formats like png, pdf, ps, eps svg, and more, making it flexible for different use cases.
Example
Here is an example that creates a thumbnail for a single .jpg image.
import matplotlib.pyplot as plt import matplotlib.image as mpimg input_image_path = "Images/Tajmahal.jpg" output_thumbnail_path = "Images/Tajmahal_thumbnail.jpg" # Load the original image img = mpimg.imread(input_image_path) # Create a thumbnail using Matplotlib thumb = mpimg.thumbnail(input_image_path, output_thumbnail_path, scale=0.15) print(f"Thumbnail generated for {input_image_path}. Saved to {output_thumbnail_path}")
Output
If you visit the folder where the images are saved you can observe both the original and output Thumbnail images as shown below −
Generating Thumbnails for multiple Images
Consider a scenario where you have multiple images in a directory, and you want to generate thumbnails for each of them.
Example
Here is an example that creates thumbnails of multiple PNG images in a directory. Save the following script as generate_thumbnails.py file.
from argparse import ArgumentParser from pathlib import Path import sys import matplotlib.image as image parser = ArgumentParser(description="Generate thumbnails of PNG images in a directory.") parser.add_argument("imagedir", type=Path) args = parser.parse_args() if not args.imagedir.is_dir(): sys.exit(f"Could not find the input directory {args.imagedir}") outdir = Path("thumbs") outdir.mkdir(parents=True, exist_ok=True) for path in args.imagedir.glob("*.png"): outpath = outdir / path.name try: fig = image.thumbnail(path, outpath, scale=0.15) print(f"Saved thumbnail of {path} to {outpath}") except Exception as e: print(f"Error generating thumbnail for {path}: {e}")
Then run the script as follows in command prompt
python generate_thumbnails.py /path/to/all_images
Output
On executing the above program, will create a directory named “thumbs” and generate thumbnails for PNG images in your working directory. If it encounters an image with a different format, it will print an error message and continue processing other images.
Saved thumbnail of Images3d_Star.png to thumbs3d_Star.png Saved thumbnail of Imagesballoons_noisy.png to thumbsballoons_noisy.png Saved thumbnail of Imagesbinary image.png to thumbsbinary image.png Saved thumbnail of Imagesblack and white.png to thumbsblack and white.png Saved thumbnail of ImagesBlack1.png to thumbsBlack1.png Saved thumbnail of ImagesBlank.png to thumbsBlank.png Saved thumbnail of ImagesBlank_img.png to thumbsBlank_img.png Saved thumbnail of ImagesCircle1.png to thumbsCircle1.png Saved thumbnail of ImagesColorDots.png to thumbsColorDots.png Saved thumbnail of Imagescolorful-shapes.png to thumbscolorful-shapes.png Saved thumbnail of Imagesdark_img1.png to thumbsdark_img1.png Saved thumbnail of Imagesdark_img2.png to thumbsdark_img2.png Saved thumbnail of Imagesdecore.png to thumbsdecore.png Saved thumbnail of Imagesdeform.png to thumbsdeform.png Saved thumbnail of ImagesDifferent shapes.png to thumbsDifferent shapes.png Error generating thumbnail for ImagesDifferent shapes_1.png: not a PNG file Saved thumbnail of ImagesEllipses.png to thumbsEllipses.png Error generating thumbnail for ImagesEllipses_and_circles.png: not a PNG file Saved thumbnail of Imagesimages (1).png to thumbsimages (1).png Saved thumbnail of Imagesimages (3).png to thumbsimages (3).png Saved thumbnail of Imagesimages.png to thumbsimages.png Saved thumbnail of Imagesimage___1.png to thumbsimage___1.png Saved thumbnail of ImagesLenna.png to thumbsLenna.png Saved thumbnail of Imageslogo-footer-b.png to thumbslogo-footer-b.png Saved thumbnail of Imageslogo-w.png to thumbslogo-w.png Saved thumbnail of Imageslogo.png to thumbslogo.png Saved thumbnail of Imageslogo_Black.png to thumbslogo_Black.png
”;