所有操作均基于 from PIL import Image, ImageDraw, ImageFilter, ImageFont。
from PIL import Image, ImageDraw, ImageFilter, ImageFont
· Image.open(path) 读取本地图片文件,返回 Image 对象。
· img.save(path, format=None, **options) 保存图像,可指定格式(如 PNG、JPEG)。
# 打开
img = Image.open('sample.jpg')
print(img.format, img.size, img.mode) # JPEG (800, 600) RGB
# 保存为 PNG
img.save('sample.png')
· img.size 返回 (宽, 高)。
· img.resize((new_w, new_h), resample=Image.LANCZOS) 改变尺寸。
· img.thumbnail(maxsize, resample=Image.LANCZOS) 等比例缩小,直接修改原对象。
# 获取尺寸
w, h = img.size
print(f'原始尺寸: {w}x{h}')
# 直接缩放到 400x300
small = img.resize((400, 300), Image.LANCZOS)
small.save('small.jpg')
# 等比例缩小到最大 200 像素
img.thumbnail((200, 200))
img.save('thumb.jpg')
· img.crop(box) box = (left, upper, right, lower),返回裁剪后的新图像。
# 裁剪左上角 200x200 区域
box = (0, 0, 200, 200)
crop_img = img.crop(box)
crop_img.save('crop.jpg')
· img.rotate(angle, expand=True, resample=Image.BICUBIC) 逆时针旋转。
· img.transpose(method) 水平/垂直翻转、转置等。
# 逆时针旋转 45°
rot = img.rotate(45, expand=True)
rot.save('rot45.jpg')
# 水平翻转
flipped = img.transpose(Image.FLIP_LEFT_RIGHT)
flipped.save('flipped.jpg')
· img.convert(mode) 常用模式:RGB、L(灰度)、RGBA、CMYK。
# 转为灰度图
gray = img.convert('L')
gray.save('gray.png')
# 添加透明通道(RGBA)
rgba = img.convert('RGBA')
rgba.save('rgba.png')
使用 ImageDraw.Draw(img) 在图像上绘制。
draw = ImageDraw.Draw(img)
# 画矩形(红色、宽度 3)
draw.rectangle([(50,50), (200,200)], outline='red', width=3)
# 画圆(蓝色填充)
draw.ellipse([(250,50), (350,150)], fill='blue')
# 写文字(需要字体文件)
font = ImageFont.truetype('arial.ttf', size=24)
draw.text((100,300), 'Hello Pillow', fill='green', font=font)
img.save('drawn.jpg')
· img.filter(filter) 常用滤镜:ImageFilter.BLUR、CONTOUR、DETAIL、EDGE_ENHANCE、SHARPEN。
blurred = img.filter(ImageFilter.BLUR)
blurred.save('blur.jpg')
sharpened = img.filter(ImageFilter.SHARPEN)
sharpened.save('sharpen.jpg')
· base_img.paste(paste_img, box, mask=None) 将一张图粘贴到另一张图上,可使用透明蒙版。
base = Image.new('RGB', (400,400), 'white')
logo = Image.open('logo.png').convert('RGBA')
# 将 logo 粘贴到右下角
base.paste(logo, (400-logo.width, 400-logo.height), logo)
base.save('merged.png')
使用 io.BytesIO 将图像保存到内存中,常用于 Flask、Django 等框架返回图片。
import io
buf = io.BytesIO()
img.save(buf, format='JPEG')
byte_data = buf.getvalue() # byte_data 可直接写入响应体
帮助快速掌握 Pillow 常用操作。若需更完整的 API 说明,请参考官方文档或对应章节的源码注释。