2 min read

Python Pillow (PIL) Module

Pillow is the friendly PIL (Python Imaging Library) fork. It adds image processing capabilities to your Python interpreter. It supports opening, manipulating, and saving many different image file formats.

Installation

pip install Pillow

Importing the Module

Although the library is installed as Pillow, you import it as PIL.

from PIL import Image

Opening and Showing Images

To load an image from a file, use the open() function in the Image module.

from PIL import Image

try:
    img = Image.open("sample.jpg")

    # Print image details
    print(f"Format: {img.format}")
    print(f"Size: {img.size}")
    print(f"Mode: {img.mode}")

    # Display the image (opens in default image viewer)
    img.show()
except FileNotFoundError:
    print("Image not found.")

Basic Manipulations

Resizing

# Resize to 300x300 pixels
new_img = img.resize((300, 300))

Rotating

# Rotate 90 degrees counter-clockwise
rotated = img.rotate(90)

Cropping

The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate.

box = (100, 100, 400, 400)
cropped = img.crop(box)

Thumbnails

The thumbnail() method modifies the image in place to create a thumbnail version no larger than the given size, preserving aspect ratio.

img.thumbnail((128, 128))

Image Filters

Pillow provides a number of predefined image enhancement filters.

from PIL import ImageFilter

blurred = img.filter(ImageFilter.BLUR)
sharpened = img.filter(ImageFilter.SHARPEN)

Saving Images

Use the save() method to save images. You can convert formats by changing the file extension.

img.save("output.png")

programming/python/python