本教程详细介绍如何在Linux环境下安装与配置Python的PIL及Pillow库,并通过实例展示基本的图像处理操作。适合初学者快速上手。
在Linux系统中使用Python进行图像处理通常会依赖两个库:PIL(Python Imaging Library)和Pillow。其中,PIL是Python的一个老牌图像处理库;而Pillow则是它的更新和维护版本,包含了所有功能并解决了许多兼容性和安装问题。
本教程将指导你在Linux上如何安装这两个库,并提供一个使用Pillow批量转换图片的实例。
通常情况下,你可以通过Python的包管理器pip来安装这些库。执行`pip install PIL==1.1.7`或`pip install Pillow==2.9.0`即可。然而,在安装过程中可能会遇到一些问题,例如*** TKINTER support not available、JPEG support not available、WEBP support not available等提示信息。这些问题通常意味着某些特定的图像格式支持没有被正确地安装。
为了解决这些依赖性的问题,你需要先在系统中安装相应的库文件:
- 对于JPEG支持,在Debian系Linux上运行`apt-get install libjpeg8-dev`;而在RedHat系系统中则使用`yum install libjpeg-devel`。
- 对于PNG的支持,需要安装zlib1g-dev(对于Debian系)或libpng-devel(针对RedHat系列)。
- 而对于WebP支持,则需执行 `apt-get install libwebp-dev` 或 `yum install libwebp-devel`。
在某些情况下,你可能还需要手动创建软链接来解决依赖性问题。例如,在Debian 7和Ubuntu 14.04上使用:
```bash
ln -s /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib/
ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib/
ln -s /usr/lib/x86_64-linux-gnu/libz.so /usr/lib/
ln -s /usr/lib/x86_64-linux-gnu/libwebp.so /usr/lib/
```
而在CentOS 6.5上,使用:
```bash
ls -s /usr/lib64/libjpeg.so /usr/lib
ls -s /usr/lib64/libz.so /usr/lib
ls -s /usr/lib64/libwebp.so /usr/lib
```
创建完软链接后,请重新安装PIL或Pillow,可以使用`pip install -I PIL==1.1.7` 或 `pip install -I Pillow==2.9.0`(其中 `-I` 表示强制重新安装)。确保所有格式都已支持。
如果在从源码安装时遇到问题,你可以下载PIL的源代码包并手动编译和安装。例如:
```bash
wget http://effbot.org/downloads/Imaging-1.1.7.tar.gz
tar -xzvf Imaging-1.1.7.tar.gz && cd Imaging-1.1.7
python setup.py install
```
如果这仍然不行,可以尝试运行`python setup.py build_ext -i`然后再重新安装。
以下是一个使用Pillow批量转换图片的简单Python代码示例:
```python
#coding=utf-8
from PIL import Image
def resize_image(input_path, output_path, size):
with Image.open(input_path) as img:
img_resized = img.resize(size)
img_resized.save(output_path)
if __name__ == __main__:
input_folder = input_folder
output_folder = output_folder
size = (800, 600)
for filename in os.listdir(input_folder):
if filename.endswith(.jpg) or filename.endswith(.png):
input_file = os.path.join(input_folder, filename)
output_file = os.path.join(output_folder, filename)
resize_image(input_file, output_file, size)
```
这段代码定义了一个函数`resize_image`,接收输入图片路径、输出图片路径和目标尺寸,然后使用Pillow打开图片并调整大小后保存。在主程序中遍历指定目录下的所有.jpg和.png文件,并调用`resize_image`进行转换。
通过这个实例,在Linux环境中你可以有效地管理和处理图像:无论是安装必要的库还是编写自动化脚本以批量处理任务都可以借助Python和Pillow轻松实现。