0
0
PythonHow-ToBeginner · 3 min read

How to Rotate Image in Python: Simple Guide with Examples

To rotate an image in Python, use the Pillow library's Image.rotate(angle) method, where angle is the degrees to rotate. This method returns a new rotated image without changing the original.
📐

Syntax

The basic syntax to rotate an image using Pillow is:

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

Explanation:

  • angle: Degrees to rotate the image counter-clockwise.
  • resample: Optional, controls quality of rotation (e.g., Image.BICUBIC).
  • expand: Optional, if True, expands output image to fit the whole rotated image.
  • center: Optional, tuple to set rotation center.
  • translate: Optional, tuple to move the image after rotation.
  • fillcolor: Optional, color to fill empty areas after rotation.
python
rotated_image = original_image.rotate(angle, resample=Image.BICUBIC, expand=True)
💻

Example

This example shows how to open an image, rotate it 45 degrees, and save the rotated image.

python
from PIL import Image

# Open an image file
original_image = Image.open('example.jpg')

# Rotate the image 45 degrees counter-clockwise and expand canvas
rotated_image = original_image.rotate(45, expand=True)

# Save the rotated image
rotated_image.save('rotated_example.jpg')

print('Image rotated and saved successfully.')
Output
Image rotated and saved successfully.
⚠️

Common Pitfalls

Common mistakes when rotating images include:

  • Not using expand=True, which can crop the rotated image.
  • Forgetting to save or display the rotated image, since rotate() returns a new image.
  • Using the wrong angle direction (rotation is counter-clockwise).
python
from PIL import Image

# Wrong: This will crop the rotated image
rotated_wrong = original_image.rotate(45)
rotated_wrong.save('cropped.jpg')

# Right: Use expand=True to keep full image
rotated_right = original_image.rotate(45, expand=True)
rotated_right.save('full_rotated.jpg')
📊

Quick Reference

Tips for rotating images with Pillow:

  • Use expand=True to avoid cropping.
  • Use resample=Image.BICUBIC for smoother rotation.
  • Rotation angle is in degrees counter-clockwise.
  • Remember to save or display the rotated image.

Key Takeaways

Use Pillow's Image.rotate(angle, expand=True) to rotate images without cropping.
Rotation angle is counter-clockwise in degrees.
Always save or display the rotated image since rotate() returns a new image.
Use resample options like Image.BICUBIC for better quality.
expand=True adjusts the canvas size to fit the rotated image fully.