作为一个天天和图像打交道的老鸟,我来分享下PIL库在实际项目中的应用经验。这些代码都是经过生产环境验证的,拿去就能用。
图像处理是个技术活,PIL库(Python Imaging Library)绝对是你的得力助手。现在它更名为Pillow,但老习惯还是叫它PIL。让我们一起来撸代码,看看如何用Python优雅地处理图片。
环境配置很简单:
pip install Pillow
要处理图片,先得把图片读进来:
from PIL import Image
# 打开图片
img = Image.open('test.jpg')
# 获取图片信息
print(f"图片尺寸: {img.size}")
print(f"图片模式: {img.mode}")
在实际项目中,经常需要调整图片尺寸。比如做个商品网站,所有商品图都得统一规格:
def resize_image(image_path, output_path, size=(800, 800)):
with Image.open(image_path) as img:
# 保持原图比例
img.thumbnail(size)
# 保存处理后的图片
img.save(output_path, quality=95)
有时候需要给图片加水印,保护版权:
def add_watermark(image_path, watermark_text):
from PIL import ImageDraw, ImageFont
img = Image.open(image_path)
# 创建一个可以在图片上绘画的对象
draw = ImageDraw.Draw(img)
# 使用系统字体,指定字体大小
font = ImageFont.truetype("arial.ttf", 36)
# 计算文字位置,放在右下角
text_width = draw.textlength(watermark_text, font=font)
position = (img.width - text_width - 10, img.height - 50)
# 绘制半透明文字
draw.text(position, watermark_text, font=font, fill=(255, 255, 255, 128))
return img
批量处理是真正提升效率的关键。写个函数批量处理整个文件夹的图片:
import os
def batch_process_images(input_dir, output_dir, process_func):
"""
批量处理图片的通用函数
process_func: 具体的处理函数
"""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(input_dir):
if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, filename)
try:
process_func(input_path, output_path)
print(f"处理成功: {filename}")
except Exception as e:
print(f"处理失败: {filename}, 错误: {str(e)}")
图片压缩是个常见需求,特别是在做网站优化的时候:
def compress_image(input_path, output_path, max_size_kb=500):
"""
压缩图片到指定大小以下
"""
quality = 95
img = Image.open(input_path)
while True:
img.save(output_path, quality=quality)
size_kb = os.path.getsize(output_path) / 1024
if size_kb <= max_size_kb or quality <= 5:
break
quality -= 5
图片滤镜效果也是常用功能:
from PIL import ImageEnhance
def apply_filter(image_path, brightness=1.0, contrast=1.0, saturation=1.0):
"""
应用图片滤镜
"""
img = Image.open(image_path)
# 调整亮度
enhancer = ImageEnhance.Brightness(img)
img = enhancer.enhance(brightness)
# 调整对比度
enhancer = ImageEnhance.Contrast(img)
img = enhancer.enhance(contrast)
# 调整饱和度
enhancer = ImageEnhance.Color(img)
img = enhancer.enhance(saturation)
return img
实际应用中,这些功能经常要组合使用。下面是个完整的示例:
def process_product_images(input_dir, output_dir):
"""
产品图片处理流程:
1. 调整尺寸
2. 加水印
3. 压缩大小
"""
def process_single_image(input_path, output_path):
# 调整尺寸
img = Image.open(input_path)
img.thumbnail((800, 800))
# 加水印
img = add_watermark(img, " MyStore 2024")
# 保存并压缩
img.save(output_path, quality=85, optimize=True)
batch_process_images(input_dir, output_dir, process_single_image)
要注意的是,图片处理比较耗CPU,处理大量图片时最好用多进程:
from multiprocessing import Pool
def parallel_process_images(input_dir, output_dir, process_func, num_processes=4):
"""
并行处理图片
"""
image_files = [f for f in os.listdir(input_dir)
if f.lower().endswith(('.png', '.jpg', '.jpeg'))]
with Pool(num_processes) as pool:
tasks = [(os.path.join(input_dir, f),
os.path.join(output_dir, f))
for f in image_files]
pool.starmap(process_func, tasks)
掌握了这些基础操作,基本上能应付80%的图片处理需求了。当然,PIL还有很多高级功能,比如图片合成、特效处理等,感兴趣的可以深入研究。记住一点:代码要优雅,处理要规范,出了问题好排查
领取专属 10元无门槛券
私享最新 技术干货