Pillow Reading Images

In this chapter, you will learn about the Pillow Image module and Image class. You will also learn how to use Pillow for reading/ loading images, displaying images, and saving images.

Image Module and Image Class

The Image class in the Pillow library is one of the most important classes. The Image class is present in the Image module, which makes it one of the most important modules in the Pillow library. Therefore it is important to first import the Image module from the Pillow library.

Importing Image Module

from PIL import Image

An object of the Pillow Image class can be created by loading an image from a file- such as loading a JPEG image from your computer. Alternatively, an object of the Image class can also be created by processing another image or creating an image from scratch.


Loading Images

The Pillow library allows you to read and write images in most of the commonly used formats. Loading an image using Pillow is as simple as it can get. You just have to call the open() function in the Image module. The path of the file to be loaded is passed as an argument to the open() function. The open() function returns an object of the Image class.

Syntax:

Image.open('<file path and name.extension>')

Example

In this example, we are using the open() function to read a PNG file present at the location "Desktop/file.png". The image is loaded in the Python variable img.

img = Image.open('file.png')

Displaying Images

You can display the image loaded in the python variable by calling the show() function on the Image class object.

Example

In this example, we will display the image we loaded in the img variable.

img.show()

The output of this will be-

Showing images by using Pillow after Reading images.

Saving Images

You can save the images you have processed using the Pillow library. Saving images using Pillow is very simple and straightforward. You call the save() method on the image and pass it the path and the name of the file you want to save the image as.

Syntax:

image_object.save('<file path and name.extension>')

Example

In this example, we will save the image we just loaded into the img Python variable as a JPG file 'file_copy.jpg'.

img.save('file_copy.jpg')

Note– We are saving the file as a JPG file while the original file was a PNG file.