什么是 PIL?
PIL(Python Imaging Library)是一个用于图像处理的强大 Python 库。它支持多种图像格式,并提供丰富的图像操作功能,如裁剪、旋转、滤镜、颜色转换等。
⚠️ 注意:原始的 PIL 项目已于 2011 年停止维护,不再兼容 Python 3。现在推荐使用其活跃的社区分支 —— Pillow。
安装 Pillow(即现代版 PIL)
只需一条命令即可通过 pip 安装:
pip install Pillow
如果你使用的是 Python 3 且系统中同时有 Python 2 和 3,建议使用:
pip3 install Pillow
验证是否安装成功
在 Python 中运行以下代码:
from PIL import Image
print("Pillow 安装成功!")
如果没有报错,说明安装成功!
常见问题与解决方法
- “No module named PIL”:你可能误用了
import PIL,正确写法是from PIL import Image。 - 权限错误:在 Linux/macOS 上可尝试加
--user参数:pip install --user Pillow - 编译错误(缺少依赖):在 Ubuntu/Debian 上先安装依赖:
sudo apt-get install libjpeg-dev zlib1g-dev
简单示例:打开并显示图片
from PIL import Image
# 打开图片
img = Image.open('example.jpg')
# 显示图片(需图形界面)
img.show()
# 获取图片信息
print(img.size, img.format, img.mode)
为什么用 Pillow 而不是 PIL?
- ✅ 兼容 Python 3
- ✅ 持续更新与维护
- ✅ 安装更简单(支持 wheel 包)
- ✅ 功能完全兼容原 PIL,并有增强
因此,当你看到教程中提到 “安装 PIL”,实际应执行 pip install Pillow。