目录:
Pillow 模块是一个功能强大且应用广泛的图像处理库,提供了丰富的图像处理功能,包括打开、操作、编辑和保存多种格式的图像文件。它支持包括 JPEG、PNG、GIF、BMP 在内的多种常见图像格式。
安装模块
$ pip3 install pillow
尽管安装的库名为 pillow,但在代码中导入时仍需使用 from PIL import … 的语法,这是为了保持与旧版 PIL 的兼容性。
open() 打开本地图片,show() 显示图片,save() 保存图片。
from PIL import Image
# 打开图像
img = Image.open("test.png")
# 显示图像(需要 GUI 环境支持)
img.show()
from PIL import Image
img = Image.open("test.png")
# 获取图像基本信息:格式、尺寸、色彩模式
print(f'图片格式: {img.format}') # PNG
print(f'图片尺寸: {img.size}') # (1662, 1361)
print(f'色彩模式: {img.mode}') # RGBA
from PIL import Image
img = Image.open("test.png")
# 转换为灰度图像('L'模式)
gray_img = img.convert('L')
gray_img.show()
图片可能会变模糊。
from PIL import Image
img = Image.open("test.png")
# 缩放图像至指定尺寸
new_size = (300, 200)
resized_img = img.resize(new_size)
resized_img.show()
from PIL import Image
img = Image.open("test.png")
# 旋转图像(逆时针角度)
rotated_img = img.rotate(45)
rotated_img.show()
from PIL import Image
img = Image.open("test.png")
# 裁剪图像,参数为 (左, 上, 右, 下) 的元组
box = (100, 100, 400, 400)
cropped_img = img.crop(box)
cropped_img.show()
from PIL import Image, ImageFilter
img = Image.open("test.png")
blurred_img = img.filter(ImageFilter.BLUR)
blurred_img.show()
↶ 返回首页 ↶