目的
应用开发中,安装包的大小是很重要的,所以需要对资源进行压缩,特别是图片。这是一个python编写的简单的.png批量压缩工具。
环境配置
python 环境配置
自然需要 python,见官网 https://www.python.org/下载
压缩API配置
亦需图片压缩 API,我们使用的是这个:https://tinypng.com 。
第一步:进入https://tinypng.com/developers,注册一个 Developer API Key,免费用户一个月有500张图的限制,付费则各有不同,请按需自取。
第二步:下载API对应的lib。参阅官网:https://tinypng.com/developers/reference/python 也有其他语言API。
终端命令:
sudo -H pip install —upgrade tinify
找到下载目录,执行命令:
sudo python setup.py
如需先安装 pip,终端命令:
easy_install pip
也可以直接下载压缩包 https://pypi.python.org/pypi/tinify 或者访问 github https://github.com/tinify/tinify-python,将 build/lib 中的 tinify 目录拷贝至 Python lib 目录下:
我的是 /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4
PS:就算不使用这个API,仅仅这个主页提供的图片压缩服务也是极好的。
使用向导
填写已申请好的 API_KEY 至 tinify.key="your_key",将脚本拷贝至需压缩图片的文件夹下,即会批量压缩该文件夹中所有大小大于 1KB 的 .png 图片。
源码(忽略第一行):
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #ba2da2}p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #000000}p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #000000; min-height: 13.0px}p.p4 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #008400}p.p5 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #d12f1b}span.s1 {font-variant-ligatures: no-common-ligatures}span.s2 {font-variant-ligatures: no-common-ligatures; color: #000000}span.s3 {font-variant-ligatures: no-common-ligatures; color: #ba2da2}span.s4 {font-variant-ligatures: no-common-ligatures; color: #272ad8}span.s5 {font-variant-ligatures: no-common-ligatures; color: #d12f1b}
import os
from tinify import tinify
from os import path
def get_file_name():
# Initialize
max_size = 1024
compressed_size = 100
dic_path = os.getcwd()
f_list = os.listdir(os.getcwd())
out_list = {}
# Read compress history
index = 0
f_history = open("history_compressed.txt", 'a+')
f_history.seek(0)
f_history_pics = {}
for line in f_history:
f_history_pics[index] = line.strip('\n')
index += 1
# do for all files under current directory
index = 0
for i in f_list:
file = dic_path + "/" + os.path.basename(i)
buffer_file = path.splitext(file)[0] + "Copy" + path.splitext(file)[1]
# compress all .pngs whitch size > max_size and not in compress history
if not contains(file, f_history_pics) and path.splitext(file)[1] == '.png' and path.getsize(file) > max_size:
f_history.write(file + "\n")
# use API from tinypng.com to compress pictures
tinify.from_file(file).to_file(buffer_file)
# replace the origin file with buffer file when their size difference is bigger than compressed_size
if (path.getsize(file) - path.getsize(buffer_file) < compressed_size):
os.remove(buffer_file)
else:
os.rename(buffer_file, file)
print(file)
index += 1
f_history.flush()
f_history.close()
return out_list
def contains(name, name_his={}):
for i in range(0, len(name_his)):
if name == name_his[i]:
return True
return False
tinify.key = "YOUR_KEY"
get_file_name()
print("finish!")