基于tinypng实现的多线程压图工具

环境:

Python3+win

import tinify
import sys
import os.path
import time
import threading
from queue import Queue
q = Queue()
# 压缩图片的key
online_key_list = [
    "你申请的key",
     # 可以继续添加  防止一个key不够
]
online_key_list_iter = iter(online_key_list)
online_key = next(online_key_list_iter)


# 在线压缩
def compress_online(sourcefile, outputfile):
    global online_key
    compresskey = online_key

    tinify.key = compresskey
    rs = False
    try:
        source = tinify.tinify.from_file(sourcefile)
        source.to_file(outputfile)
        print('压缩图片...' + outputfile)
        rs = True
        pass
    except tinify.AccountError as e:
        # Verify your API key and account limit.
        # 如果key值无效 换一个key继续压缩
        print("key值无效 换一个继续。。。")
        online_key = next(online_key_list_iter)
        compress_online(sourcefile, outputfile)  # 递归方法 继续读取
        rs = True
    except tinify.ClientError as e:
        # Check your source image and request options.
        print("Check your source image and request options. %s" % e.message)
        rs = False
        pass
    except tinify.ServerError as e:
        # Temporary issue with the Tinify API.
        print("Temporary issue with the Tinify API. %s" % e.message)
        rs = False
        pass
    except tinify.ConnectionError as e:
        # A network connection error occurred.
        print("网络故障。。。休息1秒继续")
        time.sleep(1)
        compress_online(sourcefile, outputfile)  # 递归方法 继续读取
        rs = True
        pass
    except Exception as e:
        # Something else went wrong, unrelated to the Tinify API.
        print("Something else went wrong, unrelated to the Tinify API.  %s" % e)
        rs = False
        pass

    return rs
# 遍历文件目录
def getfile(fromPath,toPath):
    if os.path.exists(toPath):
        pass
    else:
        os.mkdir(toPath)
    # root, dirs, files参数的含义:目录的路径(String);root目录下所有子目录的名字(List);root目录下非目录的名字
    # os.walk(top,topdown=True,οnerrοr=None)函数中各参数的含义:需要遍历的顶级目录的路径;默认值是“True”表示首先返回顶级目录下的文件,然后再遍历子目录中的文件;默认值为"None",表示忽略文件遍历时的错误
    for root, dirs, files in os.walk(fromPath):
        newToPath = toPath
        if len(root) > len(fromPath):  # 比较root和fromPath的字符长度
            innerPath = root[len(fromPath):]  # 字符串切割,将root字符串从第len(fromPath)个位置开始截取,不包括len(fromPath)这个位置的字符
            if innerPath[0] == '\\':  # 判断innerPath的第一个字符是不是\符号
                innerPath = innerPath[1:]  # 字符串切割,例如innerPath的值为\test,那么innerPath[1:]之后的值为test
            newToPath = os.path.join(toPath, innerPath)  # 将toPath目录和innerPath文件或文件夹拼接之后的路径赋值给newToPath

        for name in files:
            newFromFilePath = os.path.join(root, name)
            newToFilePath = os.path.join(newToPath, name)
            fileName, fileSuffix = os.path.splitext(name)  # 分解文件名的扩展名
            if fileSuffix == '.png' or fileSuffix == '.jpg':
                # 			source = tinify.from_file(newFromFilePath)
                # 			source.to_file(newToFilePath)
                # 在线压缩
                q.put((newFromFilePath,newToFilePath))
            else:
                pass

        for dirName in dirs:
            if os.path.exists(os.path.join(newToPath, dirName)):
                pass
            else:
                os.mkdir(os.path.join(newToPath, dirName))

def run():
    while True:
        if q.empty():
            break
        newFromFilePath,newToFilePath = q.get()
        if not compress_online(newFromFilePath, newToFilePath):
            print("压缩失败,检查报错信息")
            sys.exit()
            pass
        # with open(newFromFilePath, "rb") as f1:
        #     with open(newToFilePath, "wb") as f2:
        #         while True:
        #             strb = f1.read(1024)
        #             if strb == b"":
        #                 break
        #             f2.write(strb)
fromPath = ""  # source dir path
toPath = ""  # dest dir path
getfile(fromPath,toPath)
threads = [threading.Thread(target=run) for i in range(20)]
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()


思路来源:https://github.com/fengqingxiuyi/LearningNotes/tree/master/tinypng
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值