使用python批量压缩图片

以前做app开发的时候,无所谓。iOS在打包的时候会自动对图片进行无损压缩。

小程序、不自动给我压缩就算了,还限制我上传包的大小。总包限制20M就算了。主包限制2M。

寄人篱下、还能说啥、干吧 ...

tinypng官网

既然他不帮我,那我只能自己压缩了。

方案一:手动压缩。

  • 优点:不要写脚本了,使劲搬砖就行。
  • 缺点:1、没有办法记住哪些图片已经压缩了,无法避免重复劳动。2、伤眼睛。

方案二、写一个自动压缩脚本。

  • 优点:一劳永逸
  • 缺点:花时间写脚本。

综合考虑,还是写一个脚本吧。方便日后维护,后面如果有添加新的图片,直接跑一下脚本就行了。

一、准备工作。

1、注册账号。

本文使用 tinypng 网站提供的对外开放接口进行图片压缩,所以首先要在这个网站注册一个账号,并获取 API Key 官网: tinypng.com/ key 如下图 :(注意:每个key每个月可以免费压缩500张图片)

2、电脑要有python工作环境。

如果是mac电脑m1或者m2芯片,就自带的有环境了。 有没有你执行一下 ptyhon -v 或者 python3 -v 自己看一下哈 这里就不多说了,自己百度哈

3、你得有一个开发工具。

一般 python 使用 pycharm 比较多。 但是我用的 vsCode 也行。反正就写一个脚本。我所谓专不专业。

4、安装python 压缩图片依赖包

shell 复制代码
pip install --upgrade tinify

二、脚本如下:

本脚本对比其他脚本、有如下好处:

  1. 可以遍历 sourcePath 目录下的所有图片、如果你换成你的项目路径、那就会帮你的项目路劲下的所有图片进行压缩。
  2. 压缩之后,会帮已经压缩过的图片记录在txt文档中。下次再跑脚本的时候会避免重复压缩。添加新图片可以直接跑脚本。之压缩新加的图片。
python 复制代码
import os
import tinify

#图片所在目录
sourcePath = "**************"

# 保存已经压缩过的图片路劲
currentPath = os.getcwd()
fileName = "compressImageFile.txt"
compressTextPath = currentPath + '/' + fileName

# 遍历文件夹
def walkFile(file, imageList):
    for root, dirs, files in os.walk(file):
        # root 表示当前正在访问的文件夹路径
        # dirs 表示该文件夹下的子目录名list
        # files 表示该文件夹下的文件list
        # 遍历文件
        for f in files:
            result = os.path.join(root, f)
            if ('.png' in result) or ('.jpg' in result):
                imageList.append(result)

def filterHaveCompressImg(imageList):
    resultNeedCompress = []
    if os.path.exists(compressTextPath):
        for filePath in imageList:
            haveCompress = 0
            with open(compressTextPath, 'r') as file:
                for line in file:
                    lineStr = line.strip() # 去除换行符
                    if lineStr == filePath:
                        haveCompress = 1
            if haveCompress == 0:
                resultNeedCompress.append(filePath)

        return resultNeedCompress
    else:
        print('第一次压缩、创建新的txt文件')
        open(compressTextPath, "w")


def compressImage(imageList):
    print("一共有"+str(len(imageList))+"张图片"+"\n");
    resultList = filterHaveCompressImg(imageList)
    print("一共有"+str(len(resultList))+"张图片需要压缩"+"\n");
    count = 0

    for filePath in resultList:
        print("第"+str(count)+"张图片、路径为 " + filePath)
        fileDir = os.path.dirname(filePath) 
        fileName = os.path.basename(filePath)  
        unoptimizeFile = os.path.join(fileDir,fileName)
        source = tinify.from_file(unoptimizeFile)
        source.to_file(unoptimizeFile)
        file = open(compressTextPath, 'a')
        file.write(filePath + '\n')
        file.close()
        count = count + 1

def main():
    tinify.key = "**************"
    imageList = []
    walkFile(sourcePath, imageList)
    compressImage(imageList)


if __name__ == '__main__':
    print('start ==========================================\n')
    main()
    print('\nend  ==========================================\n')

如果你觉得有用点个赞再走吧。如果有疑问可以在下方给我留言。

相关推荐
SailingCoder9 分钟前
【 从“打补丁“到“换思路“ 】一次企业级 AI Agent 的架构拐点
大数据·前端·人工智能·面试·架构·agent
~央千澈~28 分钟前
抖音弹幕游戏开发之第12集:添加冷却时间机制·优雅草云桧·卓伊凡
java·服务器·前端
CappuccinoRose42 分钟前
CSS 语法学习文档(十三)
前端·css·学习·postcss·模块化·预处理器
OpenTiny社区42 分钟前
Angular Module→Standalone 架构进化解析
前端·架构·angular.js
哆啦A梦15881 小时前
Vue3魔法手册 作者 张天禹 06_监控
前端·vue.js·typescript
恋猫de小郭2 小时前
你知道不,你现在给 AI 用的 Agent Skills 可能毫无作用,甚至还拖后腿?
前端·人工智能·ai编程
用户600071819102 小时前
【翻译】用生成器实现可续充队列
前端
少云清2 小时前
【UI自动化测试】4_web自动化测试 _元素定位(重点)
前端·web前端自动化
若丶相见3 小时前
腾讯云完整部署方案:CODING + CI/CD + Docker + Nginx + K8s 扩展
前端·后端
比奇堡鱼贩3 小时前
python第五次作业
开发语言·前端·python