Home > Article > Backend Development > Python Server Programming: Image Processing with Pillow
In modern network applications, image processing is an indispensable link. Python, as a powerful server programming language, is also up to the task. Among them, Pillow is one of the most popular Python image processing libraries. Pillow provides many image processing operations, including scaling, cropping, rotation, filters, transparency, color space conversion, color adjustment, and more. This article will introduce the basic operations and examples of image processing using Pillow.
First, we need to install the Pillow library. You can use pip, the Python package manager, to install:
pip install Pillow
After the installation is complete, import the Pillow library in the Python script:
from PIL import Image
Next, we will introduce some common image operations.
img = Image.open('image.jpg')
In this example, we open the image named image.jpg.
thumbnail_size = (300, 300) img.thumbnail(thumbnail_size) img.save('image_thumbnail.jpg')
In this example, we scale the image to a maximum width or height of 300 and save it as a new image named image_thumbnail.jpg.
crop_box = (50, 50, 300, 300) img = img.crop(crop_box) img.save('image_cropped.jpg')
In this example, we crop out a rectangle of size 250x250 starting from the upper left corner of the image and save it as a new image named image_cropped.jpg.
angle = 45 img = img.rotate(angle) img.save('image_rotated.jpg')
In this example, we rotate the image 45 degrees and save it as a new image named image_rotated.jpg.
from PIL import ImageFilter img = img.filter(ImageFilter.BLUR) img.save('image_blurred.jpg')
In this example, we blur the image using the blur filter and save it as a new image named image_blurred.jpg. There are other filters to choose from, including sharpening, edge enhancement, embossing, contouring, color enhancement, and more.
from PIL import ImageEnhance enhancer = ImageEnhance.Color(img) enhanced_img = enhancer.enhance(1.5) enhanced_img.save('image_enhanced.jpg')
In this example, we use the Color Enhancer to enhance the saturation of the image to 1.5 times its original value and save it as image_enhanced.jpg new image.
In short, Pillow provides rich image processing functions that can complete many common tasks. In practical applications, we can use these operations according to needs and combine them with other Python libraries to implement more complex image processing tasks.
The above is the detailed content of Python Server Programming: Image Processing with Pillow. For more information, please follow other related articles on the PHP Chinese website!