网站优化—图片压缩

背景介绍

自己搭建的网站《联远智维》直接部署到云服务器上,由于带宽与价格息息相关,图片过大的时候会出现网站加载缓慢的问题。近来,在尽可能保证清晰度的前提下,编写python代码对图像进行压缩,最终实现了网站的优化,本推文做一个简要记录:

实现的功能点:

1.能够实现png,jpg等格式的压缩;2.能够对文件夹下所有图片进行遍历,实现图片的压缩;3.单张图片压缩后,清晰度变化不大,能够从6Mb到200kb,能够有效的提高网站流畅度;

疑问点:

图像位数的概念,从32到8能够有效减小图片的大小;

具体采用的代码为:

from PIL import Image
import os

def compress_image(input_path, quality=50, resize_factor=0.5):
    # 打开图片
    with Image.open(input_path) as img:
        original_format = img.format

        # 如果是 PNG 格式,尝试将位深度减少到 8 位
        if original_format == 'PNG':
            # 转为调色板模式(8位)
            img = img.convert('P', palette=Image.ADAPTIVE, colors=256)
            img.save(input_path, format='PNG', optimize=True, compress_level=9)  # 最大压缩级别
        else:
            # 对 JPEG 或其他格式,降低质量进行更强压缩
            if resize_factor < 1:
                width, height = img.size
                new_width = int(width * resize_factor)
                new_height = int(height * resize_factor)
                img = img.resize((new_width, new_height))

            # 保存图片时,使用较低的质量参数(如 50)来进一步压缩
            img.save(input_path, quality=quality, optimize=True)

        print(f"Compressed and replaced: {input_path}")

def batch_compress_images(input_folder, quality=50, resize_factor=0.5):
    # 遍历文件夹下所有图片文件,包括子文件夹
    for root, dirs, files in os.walk(input_folder):
        for filename in files:
            input_path = os.path.join(root, filename)
            if filename.lower().endswith(('png', 'jpg', 'jpeg', 'bmp', 'gif')):
                # 压缩每个图片并替换原始文件
                compress_image(input_path, quality, resize_factor)

# 设置输入文件夹路径
input_folder = '2022'  # 输入文件夹路径

# 调用函数进行批量压缩并替换原始文件
batch_compress_images(input_folder, quality=50, resize_factor=0.5)

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

在线客服
联远智维
我们将24小时内回复。
2025-08-23 20:17:26
您好,有任何疑问请与我们联系!
您的工单我们已经收到,我们将会尽快跟您联系!
[注意事项]
208300320
取消

选择聊天工具:

滚动至顶部