欢迎访问宙启技术站
智能推送

在Python中如何对PNG图片进行压缩

发布时间:2023-12-27 16:34:43

在Python中,可以使用Pillow库对PNG图片进行压缩。Pillow是一个Python库,可以用于处理图像文件,包括压缩、裁剪、调整大小等操作。

下面是一个对PNG图片进行压缩的例子:

首先,确保已经安装了Pillow库。可以使用pip安装:

pip install pillow

接下来,导入Pillow库和相关模块:

from PIL import Image
import os

然后,定义一个函数用于对PNG图片进行压缩:

def compress_image(input_path, output_path, max_size):
    image = Image.open(input_path)

    # 获取原始图片尺寸和宽高
    width, height = image.size

    # 按比例调整图片大小
    if width > max_size or height > max_size:
        if width > height:
            new_width = max_size
            new_height = int(new_width * height / width)
        else:
            new_height = max_size
            new_width = int(new_height * width / height)
        image = image.resize((new_width, new_height), Image.ANTIALIAS)

    # 压缩图片
    image.save(output_path, optimize=True, quality=75)

在这个函数中,首先打开输入路径的图片,然后判断图片的宽度和高度是否超过指定的最大尺寸,如果超过,则按比例调整图片大小。

然后,使用save方法将调整后的图片保存到输出路径,并设置optimize=True来启用压缩。质量参数quality可以设置压缩的质量,取值范围为0-100,值越大质量越高。

最后,遍历需要压缩的所有PNG图片,并调用上述函数进行压缩:

def compress_png_images(input_dir, output_dir, max_size):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    for filename in os.listdir(input_dir):
        if filename.endswith(".png"):
            input_path = os.path.join(input_dir, filename)
            output_path = os.path.join(output_dir, filename)
            compress_image(input_path, output_path, max_size)

在这个函数中,首先检查输出目录是否存在,如果不存在则创建。

然后,遍历输入目录中的所有文件,筛选出PNG图片,调用压缩函数对每个PNG图片进行压缩,并将压缩后的图片保存到输出目录。

最后,调用上述函数,对指定目录中的PNG图片进行压缩:

input_dir = "input"
output_dir = "output"
max_size = 500  # 指定最大尺寸为500像素
compress_png_images(input_dir, output_dir, max_size)

在这个例子中,将会压缩input目录中的所有PNG图片,并保存到output目录中。压缩后的图片尺寸不会超过500像素,并且保存的质量为75。

希望这个例子对你理解如何在Python中对PNG图片进行压缩有所帮助。