Rotate images using python

If you are working with images and if you wanna rotate or flip them to whatever angle you want, then this article is for you. Rotating the images can be made easy with python using 3 lines of code. This will require the installation of the pillow library.

What is pillow?

Python Imaging Library is a free and open-source additional library for the Python programming language that adds support for opening, manipulating, and saving many different image file formats. It is available for Windows, Mac OS X and Linux.

Installation

This python library can be installed easily from the pypi.org by running the following command in your terminal.

pip install Pillow

Once the installation is complete we are good to go.

Rotating images

Let us take this Pikachu image as the sample image. We will be rotating this left, right and also turn upside down.

We will be rotating this image to the following three angles or sides.

  1. Rotate the image by 90 degrees (left)
  2. Rotate the image by 180 degrees (upside down)
  3. Rotate the image by 270 degrees (right)
  4. Rotate the image by 360 degrees (original position)

Rotate the image by 90 degrees

Rotating the image by 90 degrees would flip the image to the left side. Let us take a look at the code and also the output of the code.

from PIL import Image
im = Image.open("pikachu.jpg")
im.rotate(90).show()

Rotating the image by 90 degrees would result in the following image.

Rotate by 90 degrees

Rotate the image by 180 degrees

Rotating the image by 180 degrees would flip the image upside down. Let us take a look at the code and also the output of the code.

from PIL import Image
im = Image.open("pikachu.jpg")
im.rotate(180).show()

Rotating the image by 180 degrees would result in the following image.

Rotating the image by 180 degrees

Rotate the image by 270 degrees

Rotating the image by 270 degrees would flip the image to the right side ( Actually there are three left turns involved in getting here). Let us take a look at the code and also the output of the code.

from PIL import Image
im = Image.open("pikachu.jpg")
im.rotate(270).show()

Rotating the image by 270 degrees would result in the following image.

Rotating the image by 270 degrees

Rotating the image by 360 degrees

360 degree rotation is a complete rotation. So if we rotate any image by 360 degrees, we will get the original image itself. So, I am not explaining that with a sample code or an image output.

Conclusion

Hope this article is useful. If you have any queries or trouble installing the packages, leave them below in the comments.

Happy coding!