• Python批量压缩图片(TinyPNG)

    • 什么是TinyPNG?
    • Mac客户端
    • 申请/查看Developer API
    • 环境准备
    • Python脚本
    • 执行批量压缩
    • 完整示例

Python批量压缩图片(TinyPNG)

什么是TinyPNG?

TinyPNG提供了PNG图片的“几乎无损”压缩服务。详细介绍TinyPNG

Mac客户端

Mac客户端下载地址
网上大多都是通过Python脚本实现,这里做一个简单的总结。

申请/查看Developer API

如果你是免费用户,那么每个developer key最多只能压500次,可通过多注册几个邮箱的方式解决次数的限制。

这里邮箱不支持QQ邮箱
如果你之前有使用邮箱申请过API Key 可以登录来查看邮箱关联的API Key

TinyPNG平台没有密码机制自能发送邮件来关联登录

环境准备

以下为笔者测试通过的Mac环境
1、Python版本2.7.10(Mac默认有安装Python)
查看Python 版本python -V,如果没有安装Mac电脑建议使用brew包管理工具安装brew install python
2、pip版本为10.0.1
pip安装参考文档

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.pypython get-pip.py

3、安装Python的tinify模板库

pip install --upgrade tinify

Python脚本

新建tinypng.py文件复制以下脚本并保存

#!/usr/bin/env python
# -*- coding: UTF-8 -*-import os
import sys
import csv
import os.path
import tinify
from PIL import Image
from optparse import OptionParser
#请替换为自己申请的Key
tinify.key = ""
png_path = []
png_path_compressed = []def get_png_path(inputPath):for p in os.listdir(inputPath):temp_path = os.path.join(inputPath,p)if os.path.isdir(temp_path):get_png_path(temp_path)else:if os.path.splitext(p)[1] == '.png' or os.path.splitext(p)[1] == 'jpg' or os.path.splitext(p)[1] == 'jpeg':print "PNG File:",os.path.join(inputPath,p)png_path.append(os.path.join(inputPath,p))        def compress_core(inputFile, outputFile, img_width):source = tinify.from_file(inputFile)if img_width is not None:resized = source.resize(method = "scale", width  = img_width)resized.to_file(outputFile)else:source.to_file(outputFile)def compress_path(path, width):print "compress_path-------------------------------------"if not os.path.isdir(path):print "这不是一个文件夹,请输入文件夹的正确路径!"returnelse:fromFilePath = path             # 源路径toFilePath = path+"/tiny"         # 输出路径print "fromFilePath=%s" %fromFilePathprint "toFilePath=%s" %toFilePathfor root, dirs, files in os.walk(fromFilePath):print "root = %s" %rootprint "dirs = %s" %dirsprint "files= %s" %filesfor name in files:fileName, fileSuffix = os.path.splitext(name)if fileSuffix == '.png' or fileSuffix == '.jpg' or fileSuffix == '.jpeg':toFullPath = toFilePath + root[len(fromFilePath):]toFullName = toFullPath + '/' + nameif os.path.isdir(toFullPath):passelse:os.mkdir(toFullPath)compress_core(root + '/' + name, toFullName, width)break                                    # 仅遍历当前目录# 仅压缩指定文件
def compress_file(inputFile, width):print "compress_file-------------------------------------"if not os.path.isfile(inputFile):print "这不是一个文件,请输入文件的正确路径!"returnprint "file = %s" %inputFiledirname  = os.path.dirname(inputFile)basename = os.path.basename(inputFile)fileName, fileSuffix = os.path.splitext(basename)if fileSuffix == '.png' or fileSuffix == '.jpg' or fileSuffix == '.jpeg':mkdir(dirname+"/tiny");png_path_compressed.append(dirname+"/tiny/"+basename)compress_core(inputFile, dirname+"/tiny/"+basename, width)else:print "不支持该文件类型!"def mkdir(path):  folder = os.path.exists(path)  if not folder:                   #判断是否存在文件夹如果不存在则创建为文件夹  os.makedirs(path)            #makedirs 创建文件时如果路径不存在会创建这个路径  print "---  new folder...  ---"  print "---  OK  ---"  else:  print "---  There is this folder!  ---"  def run(file, dir=None, width=None):if file is not None:print "仅压缩一个文件!"compress_file(file, width)                # 仅压缩一个文件passelif dir is not None:print "压缩指定目录下的文件!"compress_path(dir, width)                # 压缩指定目录下的文件passelse:print "压缩当前目录下的文件!"compress_path(os.getcwd(), width)        # 压缩当前目录下的文件def get_compressed_result():for png in png_path:run(os.path.abspath(png))rows = []row = ()for i in range(len(png_path)):img = Image.open(png_path[i])imgSize = img.sizebefore_compressed = os.stat(png_path[i]).st_sizeafter_compressed = os.stat(png_path_compressed[i]).st_sizeprint png_path[i],before_compressed,after_compressed,(before_compressed - after_compressed) *1.0/ before_compressedif imgSize[0] * imgSize[1] > 1024* 1024:too_large_scale = "True"else:too_large_scale = "False"row = (png_path[i],before_compressed,after_compressed,(before_compressed - after_compressed) *1.0/ before_compressed,imgSize[0],imgSize[1],too_large_scale)rows.append(row)header = [u'Path',u'before_compressed',u'after_compressed',u'compression_rate',u'width',u'height',u'too_large_scale']with open('compressed.csv','wb') as f:f_csv = csv.writer(f)f_csv.writerow(header)        f_csv.writerows(rows)if __name__ == "__main__":usage = '''python tinypng.py [options]-example: python tinypng.py -d xxx '''parser = OptionParser(usage)    parser.add_option('-d', dest='_path', help=u'(必选)指定游戏脚本路径')(options, args) = parser.parse_args()if not options._path:print '\n -d 参数必须设置!'print usagesys.exit(1) get_png_path(options._path)get_compressed_result()

执行批量压缩

进入tinypng.py文件所在目录执行以下命令

python tinypng.py -d ya

-d 后面为要压缩图片的文件夹路径

完整示例

要压缩的图片在/Users/Javen/Documents/dev/img/ya中,tinypng.py文件在/Users/Javen/Documents/dev/img/中,如下图所示

执行压缩命令

压缩后效果图

Python批量压缩图片(TinyPNG)相关推荐

  1. 使用Python批量压缩图片

    使用Python批量压缩图片 Python脚本 #coding:utf-8 import Image import os import os.path def picIsCorrect(fileSuf ...

  2. Python批量压缩图片

    Python批量压缩图片 代码如下 代码如下 可支持压缩指定单张图片,单个文件夹,多个文件夹,可根据自己实际场景的需求扩展丰富.话不多说,上代码. # @Time : 2021/10/14 9:16i ...

  3. 如何使用python批量压缩图片_python利用Guetzli批量压缩图片

    Google 又开源了,这次开源了一款图像算法工具 Guetzli.Guetzli,在瑞士德语中是"cookie(曲奇)"的意思,是一个针对数码图像和网页图像的 JPEG 编码器, ...

  4. 如何使用python批量压缩图片_利用Python 批量压缩图片

    方法一 直接调整宽高 先放参考资料:如何用Python智能批量压缩图片? import math from glob import glob from PIL import Image import ...

  5. 如何使用python批量压缩图片_python 实现图片批量压缩的示例

    项目中大量用到图片加载,由于图片太大,加载速度很慢,因此需要对文件进行统一压缩 一:导入包 from PIL import Image import os 二:获取图片文件的大小 def get_si ...

  6. python批量压缩图片_Python图片批量压缩到指定大小并将JPG转为PNG格式

    背景: 待压缩的图片大小有几十KB到近10M大小不等,且绝大部分图片为JPG格式.这些待压缩图片放在picture文件夹下 以及picture文件夹下的子文件夹中 现需要将picture文件夹下这些图 ...

  7. Python批量压缩图片大小并保存到相应的新文件夹,不覆盖源文件

    网上下载的小姐姐套图合集因为原图非常大,一张图十几或者几十M,一套图下来总共可能上百G,所以需要批量压缩处理一下,虽然PS也可以办到,但是代码更灵活,写个Python程序处理了一下,讲每张图长宽缩为2 ...

  8. 如何使用python批量压缩图片_Python实现批量压缩图片

    # -*- coding: utf-8 -*- """ __author__= 'Du' __creation_time__= '2018/1/5 10:06' &quo ...

  9. 如何使用python批量压缩图片_使用python脚本批量压缩图片大小

    需要安装第三方模块PIL#coding:utf-8 import Image import os #图片压缩批处理 def compressImage(srcPath,dstPath): for fi ...

  10. python 批量压缩图片

    from PIL import Image import glob, ossize = 270, 360for infile in glob.glob(r"./*.jpg"):fi ...

最新文章

  1. redhat6.5 yum源
  2. 安卓绿色联盟两项免费福利重磅发布:EMUI9.0和绿色应用2.0测试能力
  3. 基于K8S构建企业级Jenkins CI/CD平台实战(三) 之 带你实战Spring boot/Cloud 项目 CI/CD jenkins自动化构建、部署过程
  4. params(C# 参考)
  5. 程序员的灯下黑:不要忘记你的目标
  6. 【机器学习基础】数学推导+纯Python实现机器学习算法13:Lasso回归
  7. 同时对view延时执行两个动画时候的现象
  8. [机器学习-Sklearn]决策树学习与总结 (ID3, C4.5, C5.0, CART)
  9. 错过血亏!深入学习Redis集群搭建方案及实现原理
  10. 有了async/await,你可以丢掉promise链了
  11. html字体代码_第50天 HTML和css的学习
  12. python划分train val test
  13. 使用coin3d画个小模型
  14. 阵列信号处理-学习笔记002
  15. SRP Batcher,Draw Call优化,Shader SRP Batcher compatible
  16. 服务器使用笔记本网络连接外网
  17. Nim理论初探——编程之美1.12
  18. 微信支付消费者投诉消息推送接入企业微信群
  19. 【山无遮,海无拦】LeetCode题集 线性枚举之最值算法
  20. 华为机试真题 C++ 实现【处理器问题】【2022.11 Q4 新题】

热门文章

  1. 网页多种资源下载插件
  2. 谷歌地图离线包-尝试
  3. matlab液压仿真实例,基于MATLAB-simulink的液压系统动态仿真.pptx
  4. Linux下更新BIOS的方法
  5. vc6.0与vc2005配置对比
  6. 如何查看一个网页源代码的最后更新时间
  7. 好用的android剪辑软件,最好用的视频剪辑app软件有哪些?自媒体人都在用的六款app软件...
  8. HTC官方通用解锁教程(附一键解锁工具)
  9. u盘维护系统 linux,制作绝对pe+puppy U盘维护系统双系统(以下方法也可制作archlinux U盘安装)...
  10. 免费可商用字体 超好用的德拉黑体