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

推荐订阅源

M
MIT News - Artificial intelligence
WordPress大学
WordPress大学
GbyAI
GbyAI
S
SegmentFault 最新的问题
量子位
爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
MyScale Blog
MyScale Blog
人人都是产品经理
人人都是产品经理
博客园 - 叶小钗
aimingoo的专栏
aimingoo的专栏
V
Visual Studio Blog
U
Unit 42
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The Cloudflare Blog
Stack Overflow Blog
Stack Overflow Blog
博客园 - 聂微东
J
Java Code Geeks
The GitHub Blog
The GitHub Blog
Y
Y Combinator Blog
IT之家
IT之家
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)