Python Pillow - Using Image Module


To display the image, pillow library is using an image class within it. The image module inside pillow package contains some important inbuilt functions like, load images or create new images, etc.

Opening, rotating and displaying an image

To load the image, we simply import the image module from the pillow and call the, passing the image filename.

Instead of calling the Pillow module, we will call the PIL module as to make it backward compatible with an older module called Python Imaging Library (PIL). That’s why our code starts with “from PIL import Image” instead of “from Pillow import Image”.

Next, we’re going to load the image by calling the function, which returns a value of the Image object data type. Any modification we make to the image object can be saved to an image file with the save() method. The image object we received using, later can be used to resize, crop, draw or other image manipulation method calls on this Image object.


Following example demonstrates the rotation of an image using python pillow −

from PIL import Image
#Open image using Image module
im ="images/cuba.jpg")
#Show actual Image
#Show rotated Image
im = im.rotate(45)


If you save the above program as and execute, it displays the original and rotated images using standard PNG display utility, as follows −

Actual image


Rotated image (45 degrees)

Rotated Image

Attributes of Image Module

The instance of the Image class has some attributes. Let’s try to understand few of them by example −


This function is used to get the file name or the path of the image.

>>>image ='beach1.jpg')
>>> image.filename


This function returns file format of the image file like ‘JPEG’, ‘BMP’, ‘PNG’, etc.

>>> image ='beach1.jpg')
>>> image.format


It is used to get the pixel format used by the image. Typical values are “1”, “L”, “RGB” or “CMYK”.

>>> image.mode


It returns the tuple consist of height & weight of the image.

>>> image.size
(1280, 721)


It returns only the width of the image.

>>> image.width


It returns only the height of the image.

>>> image.height

It returns a dictionary holding data associated with the image.

{'jfif': 257, 'jfif_version': (1, 1), 'dpi': (300, 300), 'jfif_unit': 1, 'jfif_density': (300, 300), 'exif': b"Exif\x00\x00MM\x00*\x00\x00\x00


It returns the colour palette table, if any.

>>> image.palette

Output above − None