利用Tinify缩小图片体积(Python实现)

利用Tinify缩小图片体积(Python实现)

在博客上传图片的时候往往不需要很高的清晰度,越小的图片体积能够减少图床的空间占用。所以我一般会先通过一些工具缩小图片体积。

具有代表性的在线图片压缩网站是tinyPNG

首先在官网注册api

-> 官网:https://tinypng.com/developers

安装python依赖

pip install --upgrade tinify

在py文件中引入依赖

1
2
3
4
5
6
7
import tinify

# 填写api
tinify.key = "<your api key here>"

# 根据需要设置代理
tinify.proxy = "http://<user>:<pass>@<ip addr>:<port>"

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env python3
# coding=UTF-8
# Author: Steven Yan

import tinify
import os, time, sys


tinify.key = "<your key here>"


def welcome():
print("##########################################################")
print("## Website: StevenOS.com ##")
print("## By Steven Yan ##")
print("##########################################################")

# 用于在Windows平台设置窗口
def setWindow():
os.system("mode con cols=60 lines=30")
os.system("color 0e")
os.system("title Convert png/jpg to tiny ones")


def goodBye():
print("\nGood Bye! See you next time!\n")
for i in range(1, 4):
print("-> %s" % str(4 - i))
time.sleep(1)
sys.exit(0)

# 遍历目录中的文件
def convert(path):
for dirpath, dirs, files in os.walk(path):
for file in files:
imgpath = os.path.join(dirpath, file)
print("compressing... " + imgpath)
try:
tinify.from_file(imgpath).to_file(imgpath)
except:
# 如果不是图片文件则显示异常,但不要raiseError
print("...Failed to compress " + imgpath)
print("...Maybe it is not a PNG/JPG image.")
print("...Or, please check your internet access.\n")
print("\nFinished!")
print("Saved at " + path)
goodBye()


def getPath():
print("Please enter your image-path: ")
s = input("> ")
return s


if __name__ == "__main__":
if os.name == "nt":
setWindow()
welcome()
path = getPath()
convert(path)
else:
welcome()
path = getPath()
convert(path)

更多语言开发参考

官方文档:https://tinypng.com/developers/reference/python

Node.js

Java

打赏
  • 版权声明: 本博客采用 Apache License 2.0 许可协议。
    转载请注明出处: https://ryzenx.com/2020/08/py-tinify/

谢谢你的喜欢~

支付宝
微信