Python Pillow - Working with Images

Python Pillow - Working with Images

The Python Imaging Library (PIL), now known as Pillow, is a popular library in Python for opening, manipulating, and saving many different image file formats. Here's an overview of some of the basic tasks you can perform with Pillow:

Installation

First, make sure Pillow is installed. You can install it using pip:

pip install pillow 

Opening an Image

To open an image, use the Image module:

from PIL import Image # Open an image file img = Image.open("path_to_image.jpg") 

Displaying an Image

To display the image, you can use the show() method:

img.show() 

Saving an Image

You can save images in different formats:

img.save("new_image.png") # Save as PNG 

Resizing an Image

To resize an image, use the resize() method:

new_size = (300, 300) resized_img = img.resize(new_size) 

Cropping an Image

You can crop an image by specifying a box defining the left, upper, right, and lower pixel coordinate:

box = (100, 100, 400, 400) # (left, upper, right, lower) cropped_img = img.crop(box) 

Rotating an Image

Rotate an image by a certain degree:

rotated_img = img.rotate(90) # Rotate 90 degrees 

Flipping an Image

Flip the image horizontally or vertically:

flipped_img = img.transpose(Image.FLIP_LEFT_RIGHT) # Horizontal flip 

Creating Thumbnails

Pillow can create thumbnails that maintain aspect ratio:

img.thumbnail((100, 100)) # Resize image to fit within 100x100, maintaining aspect ratio 

Working with Filters

Pillow provides several built-in filters:

from PIL import ImageFilter blurred_img = img.filter(ImageFilter.BLUR) 

Image Enhancements

Pillow also includes functions to enhance images, such as changing contrast, brightness, etc.:

from PIL import ImageEnhance enhancer = ImageEnhance.Contrast(img) enhanced_img = enhancer.enhance(2) # Increase contrast 

Reading Image Metadata

You can access image metadata like its format, size, and mode:

print(img.format) # e.g., JPEG print(img.size) # e.g., (1920, 1080) print(img.mode) # e.g., RGB 

Conclusion

Pillow is a powerful library that provides a wide range of functionalities for image processing. These examples cover basic tasks, but Pillow's capabilities extend much further, allowing for complex image manipulations and processing.


More Tags

executorservice laravel-5.3 manifest oneway runtime-error firemonkey discord-jda capitalize odbc react-native-maps

More Programming Guides

Other Guides

More Programming Examples