How to rotate image in Pillow?

Learn how to rotate images using Python’s Pillow library with the rotate() function to adjust angles and expand parameters.

python meme to rotate

Rotating the image

For a start we will rotate image 180 degrees.

from PIL import Image

my_image = Image.open("C:/Users/pythoneo/Documents/image.jpg")

rotated_image = my_image.rotate(180, expand='True')
rotated_image.show()

python pillow image rotate 180 angle

The Pillow (PIL) library provides image manipulation capabilities, including the Image.rotate() function for rotating images at any angle.

See also  How to Implement Streaming Image Processing in Pillow

Use forward slashes (/) in image file paths instead of backslashes ($$ to ensure cross-platform compatibility in Python scripts.

The first parameter of Image.rotate() is the angle (in degrees), specifying the rotation amount in a clockwise direction.

Set the expand parameter to True in Image.rotate() to automatically resize the output image, preventing cropping of rotated corners.

See also  How to rotate a matrix with Numpy

See the example when you rotate image by custom angle. The benefit is that corners of your image fit to the window. This is image rotated 80 angles clockwise.

Python Pillow rotate image custom angle

How to Rotate Images by Custom Angles Using Pillow’s rotate() Function

When rotating images by custom angles (e.g., 80 degrees), the expand=True parameter ensures rotated corners fit within the output window without cropping.

from PIL import Image

my_image = Image.open("C:/Users/pythoneo/Documents/image.jpg")

rotated_image = my_image.rotate(80, expand=True)
rotated_image.show()

Add parameter documentation: rotate(angle, expand=True) rotates counter-clockwise by default; use negative angles for clockwise rotation.

See also  How to rename image files in a folder all to another extension?