图片压缩工具 压缩图片大小到2m以下

从论坛找的几个软件不能压缩实际是png格式但是扩展名为jpeg的图片,所以鼓捣了个能用的

软件说明:

一个用于图片压缩的Python脚本。它使用了PIL库(Pillow库的一部分)来处理图像,并通过调整图像的质量来实现压缩。

第一,定义了一个compress_image函数,它接受输入文件路径、输出文件路径和目标文件大小作为参数。该函数会打开输入文件,并将图像模式转换为RGB(如果原始图像是RGBA格式)。然后,保存原始图像并获取其大小。如果原始图像已经小于等于目标文件大小,函数直接返回。否则,通过逐渐降低图像质量,使图像大小接近目标文件大小。最终保存压缩后的图像。接下来,定义了一个compress_images函数,它接受目标文件大小作为参数。该函数会在当前目录下创建一个名为”new”的文件夹,用于存放压缩后的图像。然后,遍历当前目录下的所有文件,如果文件是图像文件(JPEG、PNG、BMP、GIF、TIFF格式),则调用compress_image函数进行压缩,并将压缩后的图像保存到”new”文件夹中。最后,在主程序中设置了目标文件大小为2MB,然后调用compress_images函数进行压缩。最后输出”图片压缩完成”的提示信息。
成品for win10下载链接:

https://keruyun.lanzoum.com/itM8Q1bdj7bi

软件使用示例: 放到需要压缩图片同目录,双击运行,直到提示按任意键退出,压缩后图片保存到同目录下new文件夹

import os
from PIL import Image

def compress_image(input_file, output_file, target_size):
    with Image.open(input_file) as img:
        # Convert RGBA to RGB if necessary
        if img.mode == 'RGBA':
            img = img.convert('RGB')

        # 保存原始图片质量
        img.save(output_file, optimize=True, quality=95)
        
        # 获取原始图片大小
        original_size = os.path.getsize(output_file)

        # 如果图片已经小于目标大小,则直接返回
        if original_size <= target_size:
            return

        # 调整压缩质量,使得图片大小接近目标大小
        quality = 70
        while original_size > target_size and quality >= 5:
            quality -= 5
            img.save(output_file, optimize=True, quality=quality)
            original_size = os.path.getsize(output_file)

def compress_images(target_size):
    # 创建存放压缩后图片的文件夹new
    os.makedirs("new", exist_ok=True)

    # 遍历当前目录下所有文件
    for file in os.listdir():
        if os.path.isfile(file) and is_image_file(file):
            input_file = file
            output_file = os.path.join("new", file)
            compress_image(input_file, output_file, target_size)

def is_image_file(file):
    try:
        with Image.open(file) as img:
            return img.format in ['JPEG', 'PNG', 'BMP', 'GIF', 'TIFF']
    except IOError:
        return False

if __name__ == "__main__":
    # 设置目标文件大小为2MB
    target_size = 2 * 1024 * 1024

    # 压缩当前目录下所有图片
    compress_images(target_size)

    print("图片压缩完成")
    
os.system("pause")

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 共47条

请登录后发表评论