惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
J
Java Code Geeks
量子位
腾讯CDC
C
Check Point Blog
小众软件
小众软件
IT之家
IT之家
I
InfoQ
Hugging Face - Blog
Hugging Face - Blog
Stack Overflow Blog
Stack Overflow Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
GbyAI
GbyAI
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
博客园_首页
S
SegmentFault 最新的问题
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
aimingoo的专栏
aimingoo的专栏
P
Proofpoint News Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Google DeepMind News
Google DeepMind News
T
Tailwind CSS Blog
Martin Fowler
Martin Fowler

Liu Zijian's Blog | 一个技术博客

使用Certbot自动续签HTTPS证书 使用Filebeat采集Nginx日志到ES Python的协程 Python中的异常 Python中的类和对象 Python的函数 Python的数据结构,推导式、迭代器和生成器 Spring AI集成多模态模型 LangChain4j多模态 LangChain Tools工具使用 Python中的模块和包 Python全局环境和虚拟环境(venv) LangChain Prompt提示词工程 LangChain4j Tools工具使用 基于Dify搭建AI智能体应用 LangChain4j RAG检索增强生成 Spring AI实现MCP Server Spring AI集成MCP Client LangChain4j Prompt提示词工程 Spring AI使用知识库增强对话功能 Spring AI实现一个智能客服 Spring AI实现一个简单的对话机器人 实现MinIO数据的每日备份 自己实现一个DNS服务 简单理解AI智能体 大模型和大模型应用 LangChain开篇 LangChain4j开篇 一个解析Excel2007的POI工具类 DataPermissionInterceptor源码解读
使用python压缩图片
Liu Zijian · 2024-10-15 · via Liu Zijian's Blog | 一个技术博客
  1. 首先Linux上面要安装一些软件包
yum install -y libjpeg-devel

yum install -y zlib-devel

yum install -y libjpeg libtiff freetype 
  1. 其次需要安装python的依赖
pip3 install tinify

pip3 install Pillow
  1. 编写并运行以下代码

import os
from PIL import Image
import tinify
from concurrent.futures import ThreadPoolExecutor



# 配置部分
input_folder = '/img'  # 要压缩的图片文件夹
whitelist = {'example1.jpg', 'important_image.png'}  # 白名单中的文件
quality = 75  # 压缩质量

def compress_image(img_path, quality):
    """
    压缩单张图片并覆盖原文件。
    
    :param img_path: 图片路径
    :param quality: 压缩质量
    """
    try:
        img = Image.open(img_path)
        img.save(img_path, optimize=True, quality=quality)
        print(f"Compressed and saved in place: {img_path}")
    except Exception as e:
        print(f"Failed to compress {img_path}: {e}")

def compress_images_in_place(input_folder, whitelist=None, quality=75):
    """
    使用 Pillow 压缩图片并覆盖原文件,支持白名单功能。使用多线程加速处理。
    
    :param input_folder: 原始图片文件夹路径
    :param whitelist: 白名单列表,包含不希望被压缩的图片文件名(可选)
    :param quality: 压缩质量,默认75
    """
    if whitelist is None:
        whitelist = set()

    # 创建一个 ThreadPoolExecutor 来处理压缩任务
    with ThreadPoolExecutor() as executor:
        futures = []

        for root, dirs, files in os.walk(input_folder):
            for file in files:
                if file in whitelist:
                    print(f"Skipping (whitelisted): {file}")
                    continue

                if file.lower().endswith(('.jpg', '.jpeg', '.png')):
                    img_path = os.path.join(root, file)
                    futures.append(executor.submit(compress_image, img_path, quality))

        # 等待所有任务完成
        for future in futures:
            future.result()

# 调用压缩函数
compress_images_in_place(input_folder, whitelist, quality)