Python使用Pillow库轻松调整图像尺寸
在图像处理任务中,调整图片大小是一个常见需求。无论是为网页优化图片、准备机器学习数据集,还是简单调整照片尺寸,Python都提供了简单高效的解决方案。本文将介绍如何使用流行的Pillow库(PIL)来轻松实现图片缩放。
为什么选择Pillow库?
Pillow是Python中最常用的图像处理库之一,它是PIL(Python Imaging Library)的一个友好分支。Pillow具有以下优势:
- 简单易用的API
- 支持多种图像格式(JPEG, PNG, BMP, GIF等)
- 丰富的图像处理功能
- 活跃的社区支持
安装Pillow
在开始之前,确保已安装Pillow库。可以通过pip快速安装:
pip install pillow
基本图片缩放方法
1. 打开图像并调整大小
from PIL import Image
def resize_image(input_path, output_path, size):
"""
调整图片大小并保存
参数:
input_path: 输入图片路径
output_path: 输出图片路径
size: 目标尺寸,格式为(宽度, 高度)
"""
with Image.open(input_path) as img:
# 使用LANCZOS重采样滤波器(高质量)
resized_img = img.resize(size, Image.LANCZOS)
resized_img.save(output_path)
# 使用示例
resize_image("input.jpg", "output.jpg", (800, 600))
2. 按比例缩放图片
有时我们需要保持宽高比,只指定一个维度:
def resize_with_aspect_ratio(input_path, output_path, max_size):
"""
按比例调整图片大小,保持宽高比
参数:
input_path: 输入图片路径
output_path: 输出图片路径
max_size: 最大宽度或高度
"""
with Image.open(input_path) as img:
width, height = img.size
# 计算缩放比例
if width > height:
new_width = max_size
new_height = int(height * (max_size / width))
else:
new_height = max_size
new_width = int(width * (max_size / height))
resized_img = img.resize((new_width, new_height), Image.LANCZOS)
resized_img.save(output_path)
# 使用示例:将图片最大边调整为500像素
resize_with_aspect_ratio("input.jpg", "output_scaled.jpg", 500)
高级缩放选项
1. 使用不同的重采样滤波器
Pillow提供了多种重采样滤波器,影响缩放质量:
Image.NEAREST: 最近邻滤波(速度快,质量低)Image.BOX: 盒式滤波Image.BILINEAR: 双线性滤波Image.HAMMING: Hamming滤波Image.BICUBIC: 双三次滤波Image.LANCZOS: Lanczos重采样(高质量,推荐)
# 使用不同滤波器比较
with Image.open("input.jpg") as img:
# 低质量快速缩放
fast_resize = img.resize((200, 200), Image.NEAREST)
fast_resize.save("fast_resize.jpg")
# 高质量缩放
high_quality = img.resize((200, 200), Image.LANCZOS)
high_quality.save("high_quality.jpg")
2. 批量缩放图片
import os
from PIL import Image
def batch_resize_images(input_folder, output_folder, size):
"""
批量缩放文件夹中的所有图片
参数:
input_folder: 输入文件夹路径
output_folder: 输出文件夹路径
size: 目标尺寸,格式为(宽度, 高度)
"""
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for filename in os.listdir(input_folder):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
input_path = os.path.join(input_folder, filename)
output_path = os.path.join(output_folder, filename)
try:
with Image.open(input_path) as img:
resized_img = img.resize(size, Image.LANCZOS)
resized_img.save(output_path)
print(f"成功处理: {filename}")
except Exception as e:
print(f"处理 {filename} 时出错: {e}")
# 使用示例
batch_resize_images("input_images", "output_images", (800, 600))
实际应用案例
1. 为网页准备缩略图
def create_thumbnail(input_path, output_path, thumbnail_size=128):
"""
创建方形缩略图
参数:
input_path: 输入图片路径
output_path: 输出缩略图路径
thumbnail_size: 缩略图边长(像素)
"""
with Image.open(input_path) as img:
# 先按比例缩放,使较小边等于缩略图大小
img.thumbnail((thumbnail_size, thumbnail_size), Image.LANCZOS)
# 创建方形画布
background = Image.new('RGBA', (thumbnail_size, thumbnail_size), (255, 255, 255, 0))
# 计算居中位置
offset = ((thumbnail_size - img.size[0]) // 2,
(thumbnail_size - img.size[1]) // 2)
background.paste(img, offset)
background.save(output_path)
# 使用示例
create_thumbnail("product.jpg", "product_thumbnail.png")
2. 调整图片大小同时保持EXIF信息
from PIL import Image, ExifTags
def resize_with_exif(input_path, output_path, size):
"""
调整图片大小并保留EXIF信息
参数:
input_path: 输入图片路径
output_path: 输出图片路径
size: 目标尺寸,格式为(宽度, 高度)
"""
with Image.open(input_path) as img:
# 获取EXIF数据
exif_data = {}
if hasattr(img, '_getexif'):
exif = img._getexif()
if exif is not None:
for tag, value in exif.items():
decoded = ExifTags.TAGS.get(tag, tag)
exif_data[decoded] = value
# 调整大小
resized_img = img.resize(size, Image.LANCZOS)
# 保存图片并写入EXIF数据(仅JPEG支持)
resized_img.save(output_path, exif=exif_data if 'JPEG' in img.format.upper() else None)
# 使用示例
resize_with_exif("photo.jpg", "photo_resized.jpg", (1024, 768))
性能优化技巧
- 批量处理:使用
Image.thumbnail()方法可以避免创建中间图像对象 - 内存管理:处理大量图片时,及时关闭图像对象或使用
with语句 - 多线程处理:对于大量图片,可以使用
concurrent.futures实现并行处理 - 选择合适格式:根据用途选择输出格式(JPEG适合照片,PNG适合图形)
常见问题解答
Q: 缩放后的图片质量不佳怎么办?
A: 使用高质量的重采样滤波器如Image.LANCZOS,并确保输出格式支持高质量(如JPEG质量参数设为95)
Q: 如何保持图片宽高比不变?
A: 使用thumbnail()方法或手动计算比例(如本文的resize_with_aspect_ratio函数)
Q: Pillow支持哪些图像格式?
A: 支持JPEG, PNG, BMP, GIF, TIFF等常见格式,完整列表见官方文档
总结
Python的Pillow库提供了强大而灵活的图片缩放功能。从简单的尺寸调整到复杂的批量处理,从保持宽高比到创建缩略图,Pillow都能轻松应对。通过选择合适的重采样滤波器和优化处理流程,你可以在质量和性能之间取得良好平衡。
到此这篇关于Python使用Pillow库轻松调整图像尺寸的文章就介绍到这了,更多相关Python Pillow调整图像尺寸内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Python Django网页界面协同过滤推荐算法实现商品管理与推荐
商品管理与推荐系统,本系统使用Python作为主要开发语言,前端采用HTML、CSS、BootStrap等技术搭建显示界面,后端采用Django框架处理用户的请求响应2023-11-11
python环境搭建和pycharm的安装配置及汉化详细教程(零基础小白版)
这篇文章主要介绍了python环境搭建和pycharm的安装配置及汉化(零基础小白版),需要的朋友可以参考下2020-08-08


最新评论