在撰写论文的时候,美观,大气,上档次的图标能够很好地给自己的论文加分,好的可视化结果也能够让审稿人赏心悦目。但是有时候在可视化图片的时候有可能原始图像过大从而很占内存;这时候就希望能够是有一个无损压缩工具来压缩图像。目前笔者尝试过TinyPNG 感觉能够达到较好的压缩效果而且基本上不影响视觉效果。而且也有对应的安装包TinyGUI, TinyGUI 是网友根据TinyPNG提供的应用程序接口开发的本地桌面端工具。它具有以下特点:
但是又到了但是环节。
本地桌面端工具用起来虽然比较方便,但是当图片比较多,或者图片存在多个文件夹下时就没那么方便了,作为一名程序猿 这时候当然想到的是用python来写一份调用API遍历文件夹的程序咯。
同样的也需要使用上面的第一步来获取API key。
# -*- coding:utf-8 -*-
# 使用tinypng API压缩项目图片
import tinify
import os
import time
from os.path import join, getsize
import math# 压缩图片的key
online_key_list = ["FCBMvlXLZzGKxwLBQ0CCl4hyrpLMWKt*","FCBMvlXLZzGKxwLBQ0CCl4hyrpLMWKt*", # 可以继续添加 防止一个key不够
]# 获取key
online_key_list_iter = iter(online_key_list)
online_key = next(online_key_list_iter)
tinifyAPi = tinify.tinifydef size_format(size, dot=2):## 文件大小 单位转化if 1 <= size < 1024:human_size = str(round(size, dot)) + 'B'# 千字节 千字节 Kilo Byteelif math.pow(1024, 1) <= size < math.pow(1024, 2):human_size = str(round(size / math.pow(1024, 1), dot)) + 'KB'# 兆字节 兆 Mega Byteelif math.pow(1024, 2) <= size < math.pow(1024, 3):human_size = str(round(size / math.pow(1024, 2), dot)) + 'MB'# 吉字节 吉 Giga Byteelif math.pow(1024, 3) <= size < math.pow(1024, 4):human_size = str(round(size / math.pow(1024, 3), dot)) + 'GB'# 太字节 太 Tera Byteelif math.pow(1024, 4) <= size < math.pow(1024, 5):human_size = str(round(size / math.pow(1024, 4), dot)) + 'TB'return human_size# 在线压缩
def compress_online(sourcefile):global online_keycompresskey = online_keytinify.key = compresskeyrs = Falseoutputfile = sourcefileold_size = getsize(sourcefile)try:source = tinifyAPi.from_file(sourcefile)source.to_file(outputfile)new_size = getsize(outputfile)sub_size = old_size - new_sizeprint('保存路径:{} | 压缩前文件大小:{}; 压缩后文件大小:{}; 压缩比例:{:.2}%'.format(outputfile, size_format(old_size),size_format(new_size), sub_size / new_size * 100))rs = Truepassexcept tinify.AccountError:# Verify your API key and account limit.# 如果key值无效 换一个key继续压缩print("key值无效 换一个继续。。。")online_key = next(online_key_list_iter)compress_online(sourcefile) # 递归方法 继续读取rs = Trueexcept tinify.ClientError:# Check your source image and request options.print("Check your source image and request options.")rs = Falsepassexcept tinify.ServerError:# Temporary issue with the Tinify API.# print("Temporary issue with the Tinify API. %s" % e.message)print("Temporary issue with the Tinify API.")rs = Falsepassexcept tinify.ConnectionError:# A network connection error occurred.print("网络故障。。。休息1秒继续")time.sleep(1)compress_online(sourcefile) # 递归方法 继续读取rs = Truepassexcept Exception:# Something else went wrong, unrelated to the Tinify API.print("Something else went wrong, unrelated to the Tinify API.")rs = Falsepassreturn rsdef fileofdir_iterate(path):folderlist = os.listdir(path) # 列举文件夹folderlist.sort()for item in folderlist:item_name = os.path.join(path, item)if os.path.isfile(item_name):compress_online(item_name)else:fileofdir_iterate(item_name)if __name__ == '__main__':dir_path = r"D:\Desktop\fig\figures\examples\GF2"fileofdir_iterate(dir_path)
上面的程序参考了:https://github.com/haoma2012/PythonProject/blob/master/ComPressPic.py。
这里作者直接把压缩后的图片替换了原始的图片,可以根据自己的需求来调整输出结果的存放位置。
以上便是本次分享,如有问题可添加笔者QQ: