Pillow(Python Imaging Library,简称PIL)是Python中一个广泛使用的图像处理库,它提供了许多功能强大的图像处理工具和函数。下面是一些Pillow库的常见用法介绍:
安装Pillow
首先,您需要确保Pillow已经安装在您的Python环境中。如果尚未安装,可以使用pip来安装它:
pip install pillow
打开和保存图像
使用Pillow,您可以轻松地打开和保存各种图像格式,例如JPEG、PNG、BMP等。以下是示例代码:
from PIL import Image
# 打开图像
img = Image.open('example.jpg')
# 保存图像
img.save('output.jpg')
调整图像尺寸
Pillow允许您调整图像的大小,以适应您的需求:
# 调整图像尺寸
new_size = (200, 200)
resized_img = img.resize(new_size)
resized_img.save('resized.jpg')
图像剪裁和旋转
您可以使用Pillow进行图像的剪裁和旋转:
# 剪裁图像
box = (100, 100, 300, 300)
cropped_img = img.crop(box)
cropped_img.save('cropped.jpg')
# 旋转图像
rotated_img = img.rotate(90) # 旋转90度
rotated_img.save('rotated.jpg')
添加文本和绘图
您可以使用Pillow在图像上添加文本和绘制各种形状:
from PIL import ImageDraw, ImageFont
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("arial.ttf", 36) # 指定字体和大小
# 添加文本
draw.text((50, 50), "Hello, Pillow!", fill=(255, 0, 0), font=font)
# 绘制矩形
draw.rectangle([100, 100, 200, 200], outline=(0, 255, 0), width=2)
img.save('text_and_shapes.jpg')
图像滤镜和效果
Pillow还提供了一些内置的滤镜和效果,可以对图像进行处理,例如模糊、锐化、颜色调整等。
from PIL import ImageFilter
# 应用滤镜
blurred_img = img.filter(ImageFilter.BLUR)
blurred_img.save('blurred.jpg')
# 锐化图像
sharpened_img = img.filter(ImageFilter.SHARPEN)
sharpened_img.save('sharpened.jpg')
结尾(文档)
这只是Pillow库的一些基本用法示例。Pillow提供了丰富的功能,可以进行更复杂的图像处理任务。您可以查阅官方文档以获取更多详细信息和示例:https://pillow.readthedocs.io/en/stable/index.html