wesley преди 6 години
ревизия
a848f2a04d
променени са 3 файла, в които са добавени 201 реда и са изтрити 0 реда
  1. 84 0
      README.md
  2. 36 0
      compress.py
  3. 81 0
      tinyimg.py

+ 84 - 0
README.md

xqd
@@ -0,0 +1,84 @@
+![](http://ww4.sinaimg.cn/large/005Xtdi2gw1f4kksnoy72j313y07yjuk.jpg)
+
+## 前言
+我们在写文章或者建网站时,经常需要对图片压缩处理,以便帮助用户节省流量和提升网站加载速度。
+
+图片压缩有很多方法,这里推荐的是[TinyPNG](https://tinypng.com/)。TinyPNG 是一个在线压缩工具,主要优点是在视觉上没有明显变化的情况下达到很高的压缩比(如我手机截屏图片大小一般为110k,压缩后能达到30k左右)。
+
+TinyPNG官网: https://tinypng.com/
+
+>
+TinyPNG支持一次最多上传20张图片,图片最大5M。
+
+如果处理的图片比较少则使用在线压缩即可,非常方便,但如果图片处理量比较大,使用在线压缩一次一次的上传下载则显得有些麻烦了,因此用Python写了一个简单的脚本,用于批量压缩图片。
+
+## 使用方法
+
+### 一.配置环境
+
+**Python:** 保证电脑中存在 Python 环境。
+
+**Tinify:** 导入Tinify
+```
+  pip install --upgrade tinify
+```
+
+### 二.申请 API key
+
+到此处申请 API key: https://tinypng.com/developers
+
+>
+一个 key 每个月可以免费压缩500张图片,可以申请多个 key。
+
+### 三.配置脚本并运行
+下载完该脚本后,你需要简单编辑一下该脚本,将申请到到API key 填写进去。
+
+```
+online_key_list = [
+    "sq5RzZVjHxVKRN0CHSBn659XPb67PyMl",
+    "rcj2WmWcPZGMDbmwDXJ69XQKGhyr6mCw", # 可以继续添加  防止一个key不够
+]
+```
+
+之后你可以将该脚本放入到需要压缩的图片的文件夹下,然后在命令行(终端)中进入到该文件夹
+
+执行如下命令批量压缩指定文件夹下大于1000k的图片:
+```
+python tinypng.py -d /wwwroot/swdz -s 1000k
+```
+或以下命令压缩指定图片:
+```
+python tinypng.py -f /wwwroot/swdz/icon1.png 
+```
+
+### 四.支持参数
+
+参数  | 参数类型 | 摘要                               | 示例
+:----:|----------|------------------------------------|-----------------------------
+ 无参 |          | 压缩根目录下所有图片文件       | `tinypng.py` 
+`-f` | 图像文件 | 压缩指定的单个文件                 | `tinypng.py -f /User/GcsSloop/demo.jpg`
+`-d` | 文件夹   | 压缩指定文件夹下所有图片文件       | `tinypng.py -d /User/GcsSloop/DemoDir`
+`-s` | 图像大小   | 压缩指定大小的图片       | `tinypng.py -s 1000K`
+ `-w` | 整型数字 | 压缩后图片的宽度,不指定则宽度不变 | `tinypng.py -w 300`
+
+**参数优先级:**
+```
+  -f > -d > 无参
+```
+如果指定了 `-f` 则只会压缩指定文件,即使后续跟了 `-d` 也不会压缩指定的文件夹
+
+```
+ -w 无冲突,均可使用
+```
+
+```
+-s 用于压缩指定文件夹下大于指定大小的图片,对-f指定图片无效
+```
+
+
+
+
+
+
+
+

+ 36 - 0
compress.py

xqd
@@ -0,0 +1,36 @@
+#!/usr/bin/env python
+# -*- coding: UTF-8 -*-
+import os
+import click
+from PIL import Image
+
+
+@click.command()
+@click.option('-d', "--dir", type=str, default='/', help="压缩文件夹下所有文件")
+@click.option('-w', "--width", type=int, default=1024, help="图片宽度,默认不变")
+
+def run(dir,width):
+    if dir is not None:
+        find_path = "find " + dir + " -regex '.*\(jpg\|JPG\|png\|PNG\|jpeg\)' -type f   -size 100k | sort -nr"
+        result = os.popen(find_path).read().split('\n')
+
+        for item in result:
+            compress_file(item, width)
+            pass
+        pass
+    else:
+        print('请指定要压缩的文件或文件夹')
+    print('End')
+
+def compress_file(item, width):
+    if item:
+        img = Image.open(item)
+        x, y = img.size
+        if x >= width:
+            convert_path = "convert -resize 50%x50% " + item + ' ' +item
+            print(item)
+            os.popen(convert_path)
+
+
+if __name__ == "__main__":
+    run()

+ 81 - 0
tinyimg.py

xqd
@@ -0,0 +1,81 @@
+#!/usr/bin/env python
+# -*- coding: UTF-8 -*-
+
+import os
+import os.path
+import click
+import tinify
+
+
+online_key_list = [
+    "sq5RzZVjHxVKRN0CHSBn659XPb67PyMl",
+    "rcj2WmWcPZGMDbmwDXJ69XQKGhyr6mCw",# 可以继续添加  防止一个key不够
+]
+online_key_list_iter = iter(online_key_list)
+online_key = next(online_key_list_iter)
+
+version = "1.0.1"  # 版本
+
+# 压缩的核心
+def compress_core(inputFile, outputFile, img_width):
+    global online_key
+    compresskey = online_key
+    tinify.key = compresskey
+    print "file = %s" % inputFile
+    try:
+        source = tinify.from_file(inputFile)
+        if img_width is not -1:
+            resized = source.resize(method="scale", width=img_width)
+            resized.to_file(outputFile)
+        else:
+            source.to_file(outputFile)
+    except tinify.AccountError, e:
+
+        online_key = next(online_key_list_iter)
+        compress_core(inputFile, outputFile, img_width)  # 递归方法 继续读取
+    except tinify.ClientError, e:
+        print(e)
+        pass
+
+
+# 仅压缩指定文件
+def compress_file(inputFile, width):
+    print "compress_file-------------------------------------"
+    if not os.path.isfile(inputFile):
+        print "这不是一个文件,请输入文件的正确路径!"
+        return
+
+    basename = os.path.basename(inputFile)
+    fileName, fileSuffix = os.path.splitext(basename)
+    if fileSuffix == '.png' or fileSuffix == '.jpg' or fileSuffix == '.jpeg':
+        compress_core(inputFile, inputFile, width)
+    else:
+        print "不支持该文件类型!"
+
+
+@click.command()
+@click.option('-d', "--dir", type=str, default='/', help="压缩文件夹下所有文件")
+@click.option('-f', "--file", type=str, default=None, help="单个文件压缩")
+@click.option('-s', "--size", type=str, default='1024k', help="需要压缩的文件大小")
+@click.option('-w', "--width", type=int, default=-1, help="图片宽度,默认不变")
+def run(dir, file, width, size):
+    if file is not None:
+        compress_file(file, width)  # 仅压缩一个文件
+        pass
+    elif dir is not None:
+        find_path = "find " + dir + " -regex '.*\(jpg\|JPG\|png\|PNG\|jpeg\)' -type f  -size +" + size + "  | sort -nr"
+        # print(find_path)
+        result = os.popen(find_path).read().split('\n')
+
+        for item in result:
+            # print(item)
+            compress_file(item, width)
+            pass
+        pass
+    else:
+        print '请指定要压缩的文件或文件夹'
+    print "结束!"
+
+
+if __name__ == "__main__":
+    run()