Rotate an Image using PIL in Python

thumbnail

In this tutorial, you will learn to create program to rotate an image using PIL in python. The Image module provides a class with the same name which is used to represent a PIL image. The following code is loads an image then the image is rotate to 90 degress and displays it using an external viewer for image.

The Syntax for rotate an image is describe as follow:
new_object = PIL.Image.Image.rotate(image_object, angle, resample=0, expand=0)
OR
new_object = image_object.rotate(angle, resample=0, expand=0)

Parameters:
image_object: It is the real image which is to be rotated.

angle: In degrees counter clockwise.

resample: An optional resampling filter. This can be one of PIL.Image.NEAREST (use nearest neighbor), PIL.Image.BILINEAR (linear interpolation in a 2×2 environment), or PIL.Image.BICUBIC (cubic spline interpolation in a 4×4 environment). If omitted, or if the image has mode “1” or “P”, it is set PIL.Image.NEAREST.

expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image.

Return Value: Returns a copy of rotated image.

The image that I used:

lena
lena

The code is show as follow.

# Importing Image module from PIL package 
from PIL import Image 
import PIL 
  
# creating an image object (main image) 
im1 = Image.open(r"D:\MyProject\Python\ImageDownloader\lena.bmp") 
  
# rotating an image 90 deg counter clockwise 
im1 = im1.rotate(90, PIL.Image.NEAREST, expand = 1) 
  
# to show specified image 
im1.show() 

The result will be show as follow.

Read more:

Back To Top