如何使用 Python 进行批量图像调整大小和压缩

管理大量高分辨率图像可能具有挑战性,尤其是在存储空间有限或您正在准备用于网络的图像时。批量调整大小和压缩图像可以节省空间,并使您的文件更易于共享或上传。在本教程中,我们将构建一个PythonPIL脚本,使用(Python 图像库)模块(现在称为)批量调整大小和压缩图像Pillow

为什么要调整图像大小并压缩?

  • 减小文件大小:较小的图像占用较少的磁盘空间并且上传和下载速度更快。
  • 提高网站性能:调整大小和压缩的图像在网页上加载速度更快,从而提高用户体验。
  • 针对不同用途进行优化:创建适合各种平台(如社交媒体、网络或印刷)的图像大小。

入门

冷库价格 www.cqzlsb.com

要创建一个调整图像大小和压缩图像的脚本,您需要安装该Pillow库,它是 Python 中用于图像处理的强大工具。

步骤 1:安装 Pillow

使用 pip 安装 Pillow 库:复制复制

pip install Pillow

第 2 步:编写 Python 脚本

下面是一个 Python 脚本,可以调整指定目录中所有图像的大小并进行压缩:复制复制

from PIL import Image
import os

def resize_and_compress_images(input_dir, output_dir, max_width, max_height, quality):
    """
    Resize and compress images in the input directory and save them to the output directory.

    Parameters:
    - input_dir: Directory containing images to process.
    - output_dir: Directory to save processed images.
    - max_width: Maximum width for resizing.
    - max_height: Maximum height for resizing.
    - quality: Quality of the output image (1-100).
    """

    # Ensure the output directory exists
    os.makedirs(output_dir, exist_ok=True)

    # Iterate through all files in the input directory
    for filename in os.listdir(input_dir):
        # Construct the full file path
        file_path = os.path.join(input_dir, filename)

        # Open the image file
        with Image.open(file_path) as img:
            # Resize the image
            img.thumbnail((max_width, max_height))

            # Save the compressed image to the output directory
            output_path = os.path.join(output_dir, filename)
            img.save(output_path, optimize=True, quality=quality)

            print(f"Processed {filename} -> {output_path}")

if __name__ == "__main__":
    input_directory = "images/input"   # Directory with original images
    output_directory = "images/output" # Directory for processed images
    max_width = 800                    # Max width for resizing
    max_height = 600                   # Max height for resizing
    quality = 85                       # Image quality (1-100)

    resize_and_compress_images(input_directory, output_directory, max_width, max_height, quality)

脚本如何工作

  1. 导入库:该脚本使用ImagePillow 中的类来处理图像处理。
  2. 设置目录:脚本采用包含原始图像的输入目录和将保存调整大小和压缩图像的输出目录。
  3. 调整图像大小:该thumbnail()方法用于在保持纵横比的同时调整图像大小,最大宽度和高度由用户设置。
  4. 压缩图像:该save()方法以指定的质量保存调整大小的图像,从而优化文件大小。
  5. 处理每个图像:脚本遍历输入目录中的所有文件,处理每个图像文件并将输出保存到指定目录。

运行脚本

  1. 设置输入和输出目录:更新input_directoryoutput_directory变量以指向您想要的文件夹。
  2. 调整调整大小和压缩设置:修改max_widthmax_heightquality变量以满足您的需要。
  3. 执行脚本:在您的 Python 环境中运行脚本来处理指定目录中的所有图像。

使用脚本的提示

  • 批处理:此脚本非常适合批处理大量图像,节省时间和精力。
  • 不同的图像格式:Pillow 支持各种图像格式,如 JPEG、PNG、GIF 等,使其能够灵活适用于不同的用例。
  • 自定义调整大小:您可以自定义调整大小逻辑来裁剪图像或根据您的要求应用不同的缩放技术。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值