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 of 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.

Examples

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')
Copy

Input image: sample-image.png

Python Pillow - Adjust Image Brightness - Brighten the image

Output Image – resize-output.png

Python Pillow – Resize Image

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.

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')
Copy

Output Image – resize-output.png

Python Pillow – Resize Image

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.

Related Tutorials

Code copied to clipboard successfully 👍