python版使用tinypng压缩图片大小

第一步,前往tinypng官网或组自己的key值。

第二步,配置uncompressResPath、compressedResPath、largeRes路径。

第三步,拷贝以下代码执行后就能得到压缩后的图片。

tinypng的压缩效果非常好,但是免费用户每个月最多只能上传压缩500张图片,想要压缩更多的图片可以赞助一下tinypng,或者注册多个账号。

tinypng压缩效果的确非常好,虽然是有损压缩,但是压缩质量很高,在不进行大幅度缩放的情况下肉眼基本上看不出来跟原图的差异,压缩比基本上在60%以上(个人使用总结)。

压缩速度会受到网速的影响,所以有时可能会很久才压缩完一张。

tinypng官网上还支持拖拽图片上传压缩的方式,有一些限制,具体可以查看官网。

coding=utf-8

import tinify
import os
import shutil
tinify.key = “填写自己的key值”
tinify.proxy = “http://user:pass@192.168.0.1:8080”

未压缩图片路径

uncompressResPath = “未压缩图片的图片根路径”;

压缩的图片存放路径

compressedResPath = “压缩完成的图片存放路径”;

用于存放检索出的符合条件的大图

largeRes = “存放检索出的符合条件的大图”;

每个月能够使用的最大压缩数量

maxMonthCompressCount = 500;
compressions_this_month = 0;
BITAXSIZE = 1024.0
KBMAXSIZE = BITAXSIZE * 1024.0
MBMAXSIZE = KBMAXSIZE * 1024.0
GBMAXSIZE = MBMAXSIZE * 1024.0
TBMAXSIZE = GBMAXSIZE * 1024.0
totalSize = 0;

压缩单张资源

def compressSimpleRes(resAbsolutePath,fileName):
global compressions_this_month;
print(“start compress res”);
print(“original Res Size:” + size_format(os.path.getsize(resAbsolutePath)));
source = tinify.from_file(resAbsolutePath);
print(“upload Res success”);
source.to_file(compressedResPath +fileName);
compressions_this_month = tinify.compression_count;
print(“left Compress Times:” + “%i”%(maxMonthCompressCount – compressions_this_month));
print(“compress res success”);
print(“compressed Res Size:” + size_format(os.path.getsize(compressedResPath +fileName)))

压缩根目录下指定数量的png资源

def compressAllPng(path):
allFile = os.listdir(path);
for eachFile in allFile:
if os.path.isdir(path + os.sep + eachFile):
compressAllPng(path + os.sep + eachFile);
else:
if(“.png” in eachFile):
if(compressions_this_month >= maxMonthCompressCount):
return
print(“res Name:” + eachFile);
compressSimpleRes(path + os.sep + eachFile,eachFile);

获得文件大小

def size_format(size):
if size < BITAXSIZE:
return ‘%i’ % size + ‘size’
elif BITAXSIZE

如果文件大于1M则将此文件copy到largeRes文件夹

if(fileSize >= KBMAXSIZE):
totalSize = totalSize + fileSize;
print(“total size:” + size_format(totalSize));
copyToDest(fileAbsolutePath);
collectLargeSizeRes(uncompressResPath);
compressAllPng(largeRes);
print(compressions_this_month);

Original: https://blog.csdn.net/min187306/article/details/120176754
Author: 从小白做起
Title: python版使用tinypng压缩图片大小

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/756141/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球