博客优化-利用tinify进行图片无损压缩

行云流水
2022-06-18 / 11 评论 / 895 阅读 / 正在检测是否收录...

前言

博客搭建有一段时间了,随着内容的增多,感觉在打开的时候加载时间越来越长。所以就想优化一下,特此记录优化过程。

分析

图片压缩脚本


# -*- coding: utf-8 -*-
"""
Created on 2022-06-19 20:42:55
---------
@summary: 图片压缩脚本
---------
@author: xwzy
"""
# pip3 install tinify

import os
import sys
import os.path
import tinify
import shutil
import datetime
import time

# API KEY
tinify.key = "xxxxx"
# API KEY
version = "1.0.1"

# 图片待处理目录
TargetPath = '/opt/myblog/app/typecho/usr/uploads/2022'

# 处理图片存放目录
TempPath = '/tmp/img'
if not os.path.exists(TempPath):
    os.mkdir(TempPath)

# 压缩的核心
def compress_core(inputFile, outputFile, img_width):
    """
    处理图片并保存处理记录
    """
    try:
        source = tinify.from_file(inputFile)
    except Exception as e:
        print(e)
        return False

    if img_width is not -1:
        resized = source.resize(method = "scale", width  = img_width)
        resized.to_file(outputFile)
    else:
        source.to_file(outputFile)

    #降低接口调用频率
    time.sleep(1)

    return True

# 压缩一个文件夹下的图片
def compress_path(path, width):
    """
    width = -1 图片尺寸不变
    """

    if not os.path.isdir(path):
        print ("{}....这不是一个文件夹,请输入文件夹的正确路径!".format(path))
        return
    else:
        fromFilePath = path             # 源路径
        toFilePath = TempPath           # 输出路径

        history_path = '{}/.history'.format(fromFilePath)
        history_array = []

        #读取图片处理记录
        if os.path.exists(history_path):
            with open(history_path, 'r') as fr:
                history_array = fr.read().split('\n')

        for root, dirs, files in os.walk(fromFilePath):
            for name in files:
                sourceFullName = root + '/' + name
                # 如若压缩过一次,则跳过
                if sourceFullName in history_array:
                    print('{}....处理过一次,skip'.format(sourceFullName))
                    continue

                fileName, fileSuffix = os.path.splitext(name)
                if fileSuffix == '.png' or fileSuffix == '.jpg' or fileSuffix == '.jpeg':
                    toFullPath = toFilePath + root[len(fromFilePath):]
                    toFullName = toFullPath + '/' + name
                    if os.path.isdir(toFullPath):
                        pass
                    else:
                        os.mkdir(toFullPath)

                    #压缩图片
                    print('{}...正在处理中...'.format(sourceFullName))
                    if compress_core(sourceFullName, toFullName, width):

                        #备份原图
                        shutil.copyfile(sourceFullName, sourceFullName+'.bak')
                        #替换愿图片
                        shutil.copyfile(toFullName, sourceFullName)

                    #保存处理记录
                    with open(history_path, 'a+') as fw:
                        fw.write(sourceFullName + '\n')

if __name__ == "__main__":
    compress_path(TargetPath, -1)
    print("替换结束:{}".format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))

python3 img_cop.py

压缩效果

访问效果对比

评论 (11)

取消
只有登录/注册用户才可评论
  1. 头像
    vimmming
    中国广东省 · MacOS · Google Chrome
    沙发

    喜欢这篇文章,作者666,文章真棒

    回复
  2. 头像
    lhui1122
    中国广东省 · Windows 10 · Google Chrome
    板凳

    这篇文章肯定会火,作者666大顺

    回复
  3. 头像
    390166317@qq.com
    中国广东省 · Windows 10 · QQ Browser
    地毯

    学习到了,感谢博主

    回复
  4. 头像
    123456
    中国山东省 · Windows 10 · Google Chrome
    第4楼

    喜欢这篇文章,作者666,文章真棒!

    回复
  5. 头像
    123
    中国湖北省 · Windows 10 · Google Chrome
    第5楼

    这篇文章肯定会火,作者666大顺

    回复
  6. 头像
    Doer
    · Windows 10 · Google Chrome
    第6楼

    这篇文章写的真不错,真详细,点个赞。

    回复
  7. 头像
    学习到了,感谢博主
    · Windows 10 · Google Chrome
    第7楼

    喜欢这篇文章,作者666,文章真棒!

    回复
  8. 头像
    空空裤兜
    · Windows 10 · Google Chrome
    第8楼

    学习到了,感谢博主

    回复
  9. 头像
    lwh
    · MacOS · Google Chrome
    第9楼

    终于找到这篇文章了,感谢作者的分享!

    回复
  10. 头像
    啊哈哈哈啊哈哈
    · Windows 10 · Google Chrome
    第10楼

    这篇文章肯定会火,作者666大顺

    回复