Python Pillow – Resize Image

Python – Resize Image using Pillow library

To resize an image with Python Pillow, you can use resize() method of PIL.Image.Image Class. You can pass parameters like resulting image size, pixel resampling filter and the box region of source to be considered.

In this tutorial, we shall learn how to resize an image using PIL, with example Python programs.

Syntax – PIL Image.resize()

The syntax of resize() method is as shown in the following code snippet.

Image.resize(size, resample=0, box=None)

where

  • size is to passed as tuple (width, height). This is the size requested for the resulting output image after resize.
  • resample is the filter that has to be used for resampling. It is optional. You can pass:
    • PIL.Image.NEAREST
    • PIL.Image.BOX
    • PIL.Image.BILINEAR
    • PIL.Image.HAMMING
    • PIL.Image.BICUBIC
    • PIL.Image.LANCZOS
  • box is an optional 4-tuple of floats giving the region of the source image which should be considered as input for resize. The values should be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used.

With proper values provided to size parameter, you can either downsize or enlarge the input image.

Example 1: Resize an image with default values

In the following example, we will read an image and resize it to (200, 200).

Python Prgoram

from PIL import Image

#read the image
im = Image.open("sample-image.png")

#image size
size=(200,200)
#resize image
out = im.resize(size)
#save resized image
out.save('resize-output.png')

Input image: sample-image.png

Python Pillow - Adjust Image Brightness - Brighten the image

Output Image – resize-output.png

The whole source image is considered for resize, as we have not provided any value for box parameter. In the next example, we will provide the box parameter and find the output image.

Example 2: Resize Image with only box of the input image

In the following example, we will provide the box parameter. By this we consider only the box area of the input image and then resize it to size.

Python Program

from PIL import Image

#read the image
im = Image.open("sample-image.png")

#image size
size = (200,200)
box = (100,100,500,400)
#resize image
out = im.resize(size, box=box)
#save resized image
out.save('resize-output.png')

Output Image – resize-output.png

If you observe, only the box part of input image is considered for the resize action.

Summary

In this tutorial of Python Examples, we learned how to resize an image, using PIL Python library.