Files
the_information_nexus/docs/tech_docs/python/Pillow.md

3.0 KiB

Pillow (PIL Fork) is an open-source Python Imaging Library that adds image processing capabilities to your Python interpreter. This library supports opening, manipulating, and saving many different image file formats and is designed to be powerful yet simple and easy to use. Pillow is a continuation of the original PIL library, actively developed and supported, making it essential for tasks involving images. Here's a concise reference guide for common use cases with Pillow:

Pillow Reference Guide

Installation

pip install Pillow

Basic Operations

Opening and Saving Images

from PIL import Image

# Open an image file
img = Image.open('path/to/image.jpg')

# Save the image in a different format
img.save('path/to/new_image.png')

Displaying Images

# Display the image
img.show()

Image Transformations

Resizing Images

# Resize the image
resized_img = img.resize((new_width, new_height))

# Maintain aspect ratio
aspect_ratio = img.width / img.height
new_width = 100
resized_img = img.resize((new_width, int(new_width / aspect_ratio)))

Cropping Images

# Crop the image
left, top, right, bottom = 100, 100, 400, 400
cropped_img = img.crop((left, top, right, bottom))

Rotating and Flipping Images

# Rotate the image
rotated_img = img.rotate(90)

# Flip the image
flipped_img = img.transpose(Image.FLIP_LEFT_RIGHT)

Applying Filters

from PIL import ImageFilter

# Apply a built-in filter
blurred_img = img.filter(ImageFilter.BLUR)

Advanced Operations

Working with Colors

# Convert to grayscale
gray_img = img.convert('L')

# Enhancing images
from PIL import ImageEnhance

enhancer = ImageEnhance.Contrast(img)
enhanced_img = enhancer.enhance(factor)  # factor > 1 for more contrast, < 1 for less

Drawing on Images

from PIL import ImageDraw

draw = ImageDraw.Draw(img)
draw.line((0, 0) + img.size, fill=128)
draw.line((0, img.size[1], img.size[0], 0), fill=128)

# Save the modified image
img.save('path/to/drawn_image.jpg')

Reading and Modifying EXIF Data

exif_data = img._getexif()
# Note: EXIF data handling can vary; consider using the 'exif' or 'piexif' libraries for complex EXIF manipulation.

Working with Thumbnails

# Generate a thumbnail
img.thumbnail((thumbnail_width, thumbnail_height))
img.save('path/to/thumbnail.jpg')

Pillow provides a comprehensive suite of image processing tools, from basic operations like opening and saving images to more complex manipulations and effects. This guide covers foundational image manipulation techniques, but Pillow's capabilities extend to a wide range of other features, including image filtering, enhancing, and more, catering to nearly any image processing task.

Pillow's ease of use and extensive functionality make it an excellent choice for image processing in Python, suitable for tasks ranging from simple script-based image modifications to complex, high-performance web applications handling image content.