python实现如何压缩图片

以下是一个使用Python实现图片等比例压缩的脚本,它可以保持图片的原始比例,同时将图片缩小到指定的最大宽度或高度。

from PIL import Image
import os

def resize_image(input_path, output_path, max_size):
    """
    等比例压缩图片
    
    参数:
    input_path (str): 输入图片路径
    output_path (str): 输出图片路径
    max_size (int): 压缩后的最大宽度或高度(保持比例)
    """
    try:
        # 打开图片
        with Image.open(input_path) as img:
            # 获取原始尺寸
            width, height = img.size
            print(f"原始尺寸: {width}x{height}")
            
            # 计算缩放比例
            if width > height:
                # 宽度为基准
                ratio = max_size / width
            else:
                # 高度为基准
                ratio = max_size / height
                
            # 计算新尺寸
            new_width = int(width * ratio)
            new_height = int(height * ratio)
            print(f"压缩后尺寸: {new_width}x{new_height}")
            
            # 等比例缩放图片
            resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
            
            # 创建输出目录(如果不存在)
            output_dir = os.path.dirname(output_path)
            if output_dir and not os.path.exists(output_dir):
                os.makedirs(output_dir)
            
            # 保存压缩后的图片
            resized_img.save(output_path)
            print(f"图片已保存至: {output_path}")
            
            return True
            
    except Exception as e:
        print(f"处理图片时出错: {str(e)}")
        return False

def batch_resize_images(input_dir, output_dir, max_size):
    """
    批量压缩目录中的图片
    
    参数:
    input_dir (str): 输入图片目录
    output_dir (str): 输出图片目录
    max_size (int): 压缩后的最大宽度或高度(保持比例)
    """
    # 支持的图片格式
    supported_formats = ('.jpg', '.jpeg', '.png', '.bmp', '.gif')
    
    # 遍历输入目录
    for filename in os.listdir(input_dir):
        # 检查文件是否为图片
        if filename.lower().endswith(supported_formats):
            input_path = os.path.join(input_dir, filename)
            output_path = os.path.join(output_dir, filename)
            
            # 压缩并保存图片
            resize_image(input_path, output_path, max_size)

if __name__ == "__main__":
    # 示例用法
    # 单个图片压缩
    resize_image(
        input_path="input.jpg",    # 输入图片路径
        output_path="output.jpg",  # 输出图片路径
        max_size=800               # 最大尺寸(宽度或高度)
    )
    
    # 批量压缩(取消注释使用)
    # batch_resize_images(
    #     input_dir="input_images",  # 输入图片目录
    #     output_dir="output_images",# 输出图片目录
    #     max_size=800               # 最大尺寸(宽度或高度)
    # )
    


这个脚本的主要功能和特点:

  1. 使用Pillow库进行图片处理,支持多种常见图片格式(JPG、PNG、BMP、GIF等)
  2. 保持图片原始比例进行压缩
  3. 可以指定压缩后的最大宽度或高度(以较大的一边为基准)
  4. 提供了单个图片压缩和批量压缩两种模式
  5. 包含异常处理,确保程序稳定运行
  6. 自动创建输出目录(如果不存在)
  7. 使用LANCZOS重采样算法,保证压缩后的图片质量

使用前需要安装Pillow库:pip install pillow

你可以根据需要修改示例中的文件路径和最大尺寸参数,也可以根据实际需求扩展脚本功能,比如添加质量控制参数等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值