How To Use Pillow in Python

In this tutorial, you will learn how to use the Python Imaging Library (PIL) fork, Pillow, to manipulate and work with images in Python. The pillow is a powerful and easy-to-use library that enables you to perform various image processing tasks such as opening, resizing, cropping, and even adding watermarks to images.

Step 1: Install Pillow

To get started, you need to install the library using pip:

Once installed, check the installation by importing the package and checking its version:

Step 2: Opening Images

To open an image using Pillow, you can use the Image.open() function. Let’s say we have an image file named “example.jpg”:

Step 3: Displaying Images

To display the image we opened in the previous step, you can use the show() method:

Step 4: Resizing Images

To resize an image, you can use the resize() method. It takes the desired size as a tuple containing the width and height of the new image. Here is an example of resizing an image to 200×200 pixels:

Step 5: Cropping Images

You can crop an image using the crop() method. This method takes a tuple containing the left, upper, right, and lower pixel coordinates of the cropping box. The example below crops the image to a 100×100 pixels box starting at (10, 10):

Step 6: Rotating and Flipping Images

To rotate an image, you can use the rotate() method, which takes the number of degrees as its argument. The following example rotates the image by 45 degrees:

You can also flip images using the transpose() method, which takes a transpose operation as its argument:

Step 7: Saving Images

After processing an image, you can save it to a file using the save() method. The method takes the file path and, optionally, the format:

Full Code

Conclusion

You have now explored the basics of using Pillow for image processing in Python. With this powerful library, you can easily manipulate images in various ways such as resizing, cropping, and rotating them, among others.

This tutorial should provide you with a solid foundation, so feel free to explore the official Pillow documentation to learn about more advanced capabilities of the library.