rotate a png 180 degrees in python

To rotate a PNG (or any image format) by 180 degrees in Python, we can use the rotate() method of the PIL (Python Imaging Library) module, which is now known as Pillow.

Here is an example code snippet that rotates an image called image.png located in the same directory as the script, by 180 degrees:

main.py
from PIL import Image

# Open the image file
image = Image.open("image.png")

# Rotate the image by 180 degrees
rotated_image = image.rotate(180)

# Save the rotated image as a PNG
rotated_image.save("rotated_image.png")
221 chars
11 lines

In this example, we first import the Image class from the PIL module, open the original image.png file using Image.open(), rotate it by 180 degrees using rotate(), and finally save the rotated image as a new file called rotated_image.png.

Note that Image.rotate() returns a new Image object that represents the rotated image. The original image is not modified.

gistlibby LogSnag