Compress images using TinyPNG API

Compress images using TinyPNG API

When writing a paper, beautiful, grand, and high-grade icons can add points to your paper, and good visualization results can also please reviewers. But sometimes when visualizing pictures, the original image may be too large and occupy a lot of memory; in this case, we hope to have a lossless compression tool to compress the image. At present, the author has tried TinyPNG and feels that it can achieve better compression effects and basically does not affect the visual effects. And there is also a corresponding installation package TinyGUI . TinyGUI is a local desktop tool developed by netizens based on the application program interface provided by TinyPNG. It has the following characteristics:

  • There is no limit to a single image of up to 5M
  • No limit on the number of compressed images
  • Free and easy to use, just drag and drop images into the interface to compress them

Desktop usage tutorial

  1. TinyGUI needs to use the API of TinyPNG. Here, open the Developer API first , fill in the user name and email, and then click " Get Your API key ". When the page displays "We have sent you an email with a link to your API key!" you can go to the mailbox to find the received API key.
    Insert image description here
  2. Open TinyGUI, enter the API you just received in the "Set your API Key" box (it may be in the trash), and then choose to save.
    Insert image description here
  3. Select "Select image file" to upload the image that needs to be compressed, or directly drag the image to the "Drag image here" area
    Insert image description here
  4. Then you can start waiting for image compression. You can see that TinyPNG can compress a 1.5MB image to 637.4KB, a compression of 57%, which is very good.
    Insert image description here

But the but phase has come again.
Although the local desktop tool is more convenient to use, it is not so convenient when there are many pictures or the pictures are stored in multiple folders. As a programmer, of course, what I think of at this time is to use python to write an API call A program for traversing folders.

Python calls TinyPNG API to traverse folders and compress images

You also need to use the first step above to obtain the 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.tinify

def size_format(size, dot=2):
    ## 文件大小 单位转化
    if 1 <= size < 1024:
        human_size = str(round(size, dot)) + 'B'
    # 千字节 千字节 Kilo Byte
    elif math.pow(1024, 1) <= size < math.pow(1024, 2):
        human_size = str(round(size / math.pow(1024, 1), dot)) + 'KB'
    # 兆字节 兆 Mega Byte
    elif math.pow(1024, 2) <= size < math.pow(1024, 3):
        human_size = str(round(size / math.pow(1024, 2), dot)) + 'MB'
    # 吉字节 吉 Giga Byte
    elif math.pow(1024, 3) <= size < math.pow(1024, 4):
        human_size = str(round(size / math.pow(1024, 3), dot)) + 'GB'
    # 太字节 太 Tera Byte
    elif 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_key
    compresskey = online_key
    tinify.key = compresskey
    rs = False
    outputfile = sourcefile
    old_size = getsize(sourcefile)
    try:
        source = tinifyAPi.from_file(sourcefile)
        source.to_file(outputfile)
        new_size = getsize(outputfile)
        sub_size = old_size - new_size
        print('保存路径:{} | 压缩前文件大小:{}; 压缩后文件大小:{}; 压缩比例:{:.2}%'.format(outputfile, size_format(old_size),
                                                                     size_format(new_size), sub_size / new_size * 100))
        rs = True
        pass
    except tinify.AccountError:
        # Verify your API key and account limit.
        # 如果key值无效 换一个key继续压缩
        print("key值无效 换一个继续。。。")
        online_key = next(online_key_list_iter)
        compress_online(sourcefile)  # 递归方法 继续读取
        rs = True

    except tinify.ClientError:
        # Check your source image and request options.
        print("Check your source image and request options.")
        rs = False
        pass
    except 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 = False
        pass
    except tinify.ConnectionError:
        # A network connection error occurred.
        print("网络故障。。。休息1秒继续")
        time.sleep(1)
        compress_online(sourcefile)  # 递归方法 继续读取
        rs = True
        pass
    except Exception:
        # Something else went wrong, unrelated to the Tinify API.
        print("Something else went wrong, unrelated to the Tinify API.")
        rs = False
        pass
    return rs


def 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)

The above program refers to: https://github.com/haoma2012/PythonProject/blob/master/ComPressPic.py .
Here the author directly replaces the original image with the compressed image, and can adjust the storage location of the output results according to his own needs.
That’s it for this sharing.

If you have any questions, please contact: [email protected] ; please note your name + school

Guess you like

Origin blog.csdn.net/fovever_/article/details/127942929
Recommended