python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python Pillow调整图像尺寸

Python使用Pillow库轻松调整图像尺寸

作者:detayun

在图像处理任务中,调整图片大小是一个常见需求,本文将介绍如何使用流行的Pillow库(PIL)来轻松实现图片缩放,感兴趣的小伙伴可以了解下

在图像处理任务中,调整图片大小是一个常见需求。无论是为网页优化图片、准备机器学习数据集,还是简单调整照片尺寸,Python都提供了简单高效的解决方案。本文将介绍如何使用流行的Pillow库(PIL)来轻松实现图片缩放。

为什么选择Pillow库?

Pillow是Python中最常用的图像处理库之一,它是PIL(Python Imaging Library)的一个友好分支。Pillow具有以下优势:

安装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提供了多种重采样滤波器,影响缩放质量:

# 使用不同滤波器比较
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))

性能优化技巧

  1. 批量处理:使用Image.thumbnail()方法可以避免创建中间图像对象
  2. 内存管理:处理大量图片时,及时关闭图像对象或使用with语句
  3. 多线程处理:对于大量图片,可以使用concurrent.futures实现并行处理
  4. 选择合适格式:根据用途选择输出格式(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调整图像尺寸内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文