How to Rotate Images with Pillow Library in Python


In this example, we will see how to display images using the library Pillow in Python. 

The operation of the geometric transformation of images mainly includes the following aspects:

  • Change the image size: You can use the resize() method to change the size of the image. The usage is: resize((width, height))
  • Rotate image: You can use the rotate() method to turn the angle of the image. The usage is: rotate(angle)
  • Reverse the image: You can use the transpose() method to reverse the image. The usage is: transpose(method)

The parameter method can be the following: FLIP_LEFT_RIGHT, FLIP_TOP_BOTTOM, ROTATE_90, ROTATE_180, or ROTATE_270.

This example will create four graphics, from left to right, the original graphics, using the rotate() method to rotate the 45° angle, the transpose() method to rotate the 90° angle, and the resize() method to change the image size to 1/4 of the original size.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# rotateImages.py

from tkinter import *
from PIL import Image, ImageTk

win = Tk()
win.title(string = "Image Rotation")

# open an image
path = "F:/logos/"
imgFile1 = Image.open(path + "superman.png")

img1 = ImageTk.PhotoImage(imgFile1)

label1 = Label(win, width=162, height=160, image=img1)
label1.pack(side=LEFT)

# rotate 45°
imgFile2 = imgFile1.rotate(45)
img2 = ImageTk.PhotoImage(imgFile2)

label2 = Label(win, width=162, height=160, image=img2)
label2.pack(side=LEFT)

# rotate 90°
imgFile3 = imgFile1.transpose(Image.ROTATE_90)
img3 = ImageTk.PhotoImage(imgFile3)

label3 = Label(win, width=162, height=160, image=img3)
label3.pack(side=LEFT)

# reduce the image size to 1/4
width, height = imgFile1.size
imgFile4 = imgFile1.resize((int(width/2), int(height/2)))
img4 = ImageTk.PhotoImage(imgFile4)
# display the original image
label4 = Label(win, width=162, height=160, image=img4)
label4.pack(side=LEFT)

win.mainloop()

4. Data

superman.png: this is the image that we’re going to rotate.

5. Results

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments