Python Pillow uses the Image module
Python Pillow Using the Image Module
To display images, the Pillow library uses an Image class. The Image module in the Pillow package contains important built-in functions for loading images or creating new ones.
Opening, Rotating, and Displaying an Image
To load an image, we simply import the Image module from Pillow and call Image.open() , passing the image filename.
Instead of calling the Pillow module, we will call the PIL module for backward compatibility with an older module called the Python Imaging Library (PIL). This is why our code begins with “from PIL import Image” instead of “from Pillow import Image“.
Next, we load the image by calling the Image.open() function, which returns an Image object. Any modifications we make to the image object can be saved to an image file using the save() method. The image object we receive using Image.open() can later be used to resize, crop, draw, or perform other operations on it.
Example
The following example demonstrates the process of rotating an image using Python Pillow
from PIL import Image
#Open image using Image module
im = Image.open("images/cuba.jpg")
#Show actual Image
im.show()
#Show rotated Image
im = im.rotate(45)
im.show()
Output
If you save the above program as Example.py and execute it, it will display the original and rotated images using standard PNG display tools as shown below
Actual Image
Rotated image (45 degrees)
Image Module Properties
Image class instances have several properties. Let’s explore some of these properties through an example.
Image.filename
This function is used to get the file name or path of an image.
>>>image = Image.open('beach1.jpg')
>>> image.filename
'beach1.jpg'
Image.format
This function returns the file format of the image file, such as ‘JPEG’, ‘BMP’, ‘PNG’, etc.
>>> image = Image.open('beach1.jpg')
>>>
>>> image.format
'JPEG'
Image.mode
This function is used to get the pixel format used by the image. Typical values are “1”, “L”, “RGB”, or “CMYK”.
>>> image.mode
'RGB'
Image.size
It returns a tuple consisting of the image’s height and weight.
>>> image.size
(1280, 721)
Image.width
It only returns the image’s width.
>>> image.width
1280
Image.height
It only returns the image’s height.
>>> image.height
721
Image.info
This returns a dictionary holding data related to the image.
>>> image.info
{'jfif': 257, 'jfif_version': (1, 1), 'dpi': (300, 300), 'jfif_unit': 1, 'jfif_density': (300, 300), 'exif': b"Exifx00x00MMx00*x00x00x00
....
....
xebx00x00'x10x00x00xd7xb3x00x00x03xe8"}
Image.palette
This returns the palette table, if any.
>>> image.palette
Above Output – None