Python Pillow – Rotate Image 45, 90, 180, 270 degrees

Python Pillow – Rotate Image

To rotate an image by an angle with Python Pillow, you can use rotate() method on the Image object. rotate() method rotates the image in counter clockwise direction.

In this tutorial, we shall learn how to rotate an image, using PIL Python library, with the help of example programs.

Syntax of PIL Image.rotate()

The syntax of rotate() method is as shown in the following code block.

Image.rotate(angle, resample=0, expand=0, center=None, translate=None, fillcolor=None)

where

Examples

1: Rotate given image by 45 degrees

In the following example, we will rotate the image by 45 degrees in counter clockwise direction.

Python Program

from PIL import Image

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

# Rotate image
angle = 45
out = im.rotate(angle)
out.save('rotate-output.png')

Input Image – sample-image.png

Output Image – rotate-image.png

The size of the original image is preserved. You can make the size of the output image adjust to the rotation.

2. Rotate image and adjust the output size

In the following example, we will adjust the size of output image to the rotation, by using the parameter expand=True.

from PIL import Image

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

# Rotate image
angle = 45
out = im.rotate(angle, expand=True)
out.save('rotate-output.png')

Output Image

3. Rotate image by 90 degrees

You can rotate an image by 90 degrees in counter clockwise direction by providing the angle=90. We also give expand=True, so that the rotated image adjusts to the size of output.

from PIL import Image

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

# Rotate image by 90 degrees
angle = 90
out = im.rotate(angle, expand=True)
out.save('rotate-output.png')

4. Rotate image by 180 degrees

In this Python Pillow example, we will rotate the image by 180 degrees.

from PIL import Image

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

# Rotate image by 180 degrees
angle = 180
out = im.rotate(angle, expand=True)
out.save('rotate-output.png')

Output Image

Summary

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

Related Tutorials

Privacy Policy Terms of Use

SitemapContact Us