Pillow Image 模块

Pillow Image 模块 全解析

核心中的核心 —— 所有图像操作的起点与终点


1. 模块导入

from PIL import Image

Image 是 Pillow 的 核心类,几乎所有图像操作都围绕它展开。


2. Image.open() —— 打开图像

img = Image.open("photo.jpg")

支持格式(30+ 种)

格式扩展名透明
JPEG.jpg, .jpegYesYesNo
PNG.pngYesYesYes
GIF.gifYesYesYes (动画)
BMP.bmpYesYesNo
WebP.webpYesYesYes
TIFF.tif, .tiffYesYesYes
ICO.icoYesYesYes

3. Image 对象属性(只读)

属性说明示例
img.format文件格式"JPEG"
img.size尺寸 (w, h)(1920, 1080)
img.width宽度1920
img.height高度1080
img.mode色彩模式"RGB", "RGBA", "L"
img.info元数据字典{'dpi': (300, 300)}
print(img.format, img.size, img.mode)
# 输出: JPEG (1920, 1080) RGB

4. 图像模式(Mode)详解

模式说明通道用途
"1"二值(黑白)1黑白图、验证码
"L"灰度(8位)1灰度图
"LA"灰度 + 透明2透明灰度
"P"调色板(256色)1GIF
"RGB"真彩色3标准彩色
"RGBA"真彩 + 透明4PNG 透明图
"CMYK"印刷四色4印刷
"YCbCr"视频色彩3JPEG 内部
img.convert("L")      # 转灰度
img.convert("RGBA")   # 强制带透明

5. 核心方法速查表

方法功能返回
img.convert(mode)模式转换Image
img.resize((w,h))缩放Image
img.thumbnail((w,h))等比缩放(原地修改)
img.crop((l,t,r,b))裁剪Image
img.rotate(angle, expand=False)旋转Image
img.transpose(method)翻转/转置Image
img.save(path, **options)保存
img.show()系统查看器显示
img.copy()深拷贝Image
img.close()关闭文件(大图推荐)

6. 关键方法详解

convert() —— 模式转换

gray = img.convert("L")           # 灰度
rgb = img.convert("RGB")          # 去透明
palette = img.convert("P")        # 256色

resize() vs thumbnail()

方法是否保持比例是否修改原图推荐场景
resize((w,h))No返回新图固定尺寸
thumbnail((w,h))Yes修改原图缩略图
# 固定尺寸(可能变形)
resized = img.resize((800, 600))

# 等比缩放(推荐)
thumb = img.copy()
thumb.thumbnail((400, 400))  # 最大 400x400

crop() —— 精确裁剪

box = (left, upper, right, lower)
cropped = img.crop((100, 100, 500, 400))

九宫格切割示例

w, h = img.size
step_w, step_h = w//3, h//3
for i in range(3):
    for j in range(3):
        box = (j*step_w, i*step_h, (j+1)*step_w, (i+1)*step_h)
        img.crop(box).save(f"grid_{i}_{j}.jpg")

rotate() —— 旋转

img.rotate(90)                    # 顺时针 90°
img.rotate(45, expand=True)       # 45° + 扩展画布
img.rotate(180, fillcolor="white") # 填充背景色

transpose() —— 翻转

from PIL import Image

img.transpose(Image.FLIP_LEFT_RIGHT)   # 左右翻转
img.transpose(Image.FLIP_TOP_BOTTOM)   # 上下翻转
img.transpose(Image.ROTATE_90)         # 旋转 90°(等价 rotate)

常量列表:

Image.FLIP_LEFT_RIGHT
Image.FLIP_TOP_BOTTOM
Image.ROTATE_90
Image.ROTATE_180
Image.ROTATE_270
Image.TRANSPOSE
Image.TRANSVERSE

save() —— 保存图像

img.save("output.jpg", quality=95)           # JPEG 质量
img.save("output.png", optimize=True)        # PNG 优化
img.save("output.webp", lossless=True)       # WebP 无损
img.save("output.ico", sizes=[(32,32)])      # 多尺寸 ICO

7. 创建新图像

# 纯色背景
new_img = Image.new("RGB", (400, 300), color="skyblue")

# 透明画布
transparent = Image.new("RGBA", (200, 200), (0,0,0,0))

# 从数组创建
import numpy as np
array = np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8)
img_from_array = Image.fromarray(array)

8. 内存管理(大图必备)

# 方式1:with 自动关闭
with Image.open("big.tif") as img:
    img = img.resize((1000, 1000))
    img.save("small.jpg")

# 方式2:手动关闭
img = Image.open("huge.jpg")
# ...处理
img.close()  # 释放文件句柄

9. 高级:Imagenumpy 互转

import numpy as np

# Image → numpy
array = np.array(img)           # shape: (h, w, c)
array = np.asarray(img)         # 更高效

# numpy → Image
img = Image.fromarray(array)

注意:array 必须是 uint8 类型,范围 [0,255]


10. 完整示例:图像处理流水线

from PIL import Image

def process_pipeline(input_path, output_path):
    # 1. 打开 + 自动关闭
    with Image.open(input_path) as img:
        # 2. 转为 RGB
        img = img.convert("RGB")

        # 3. 等比缩放
        img.thumbnail((800, 800))

        # 4. 中心裁剪正方形
        w, h = img.size
        size = min(w, h)
        left = (w - size) // 2
        top = (h - size) // 2
        img = img.crop((left, top, left+size, top+size))

        # 5. 保存
        img.save(output_path, quality=95, optimize=True)

    print(f"处理完成: {output_path}")

# 使用
process_pipeline("input.jpg", "output_square.jpg")

Image 方法速查卡(打印即用)

img = Image.open("x.jpg")

img.format      # 格式
img.size        # (w,h)
img.mode        # 模式

img.convert("L")        # 转灰度
img.resize((800,600))   # 缩放
img.thumbnail((400,400))# 等比缩放
img.crop((0,0,100,100)) # 裁剪
img.rotate(90)          # 旋转
img.transpose(Image.FLIP_LEFT_RIGHT)  # 翻转
img.save("out.jpg")     # 保存
img.show()              # 显示

官方文档

https://pillow.readthedocs.io/en/stable/reference/Image.html


一句话总结

Image 模块 = Pillow 的心脏
打开 → 处理 → 保存,全程围绕 Image 对象!


需要我为你生成:

  • Image 模块思维导图
  • 交互式 Jupyter Notebook 演示
  • 命令行图像处理工具(基于 Image)

欢迎继续提问!

类似文章

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注