python 用于Google图像压缩实用程序zopflipng(PNG)和guetzli(JPG)的快速和脏的包装器。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 用于Google图像压缩实用程序zopflipng(PNG)和guetzli(JPG)的快速和脏的包装器。相关的知识,希望对你有一定的参考价值。

#!/usr/bin/env python

"""goptim: PNG/JPG image optimizer based on Google Open-Source projects

Requires:
    zopflipng (https://github.com/google/zopfli, `make zoplipng`)
    guetzli (https://github.com/google/guetzli/, `make`)
"""

import sys
import getopt
import os.path
import subprocess
import shutil
import uuid
import time
from datetime import datetime

files = []
processes = []

def main():
    '''Runs the main command logic'''
    # Parse options and arguments
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'h', ['help'])
    except getopt.GetoptError as err:
        # Print help information and exit
        print str(err)
        usage()
        sys.exit(2)

    for opt in opts:
        if opt in ('-h', '--help'):
            usage()
            sys.exit()
        else:
            assert False, "unhandled option"

    for item in args:
        if os.path.isdir(item):
            for filename in os.listdir(item):
                check_file(item + '/' + filename)
        else:
            check_file(item)

    if files:
        count = 1
        doneCount = 1
        total = len(files)
        out = open('/tmp/optim.log', 'a')
        out.write(datetime.now().strftime("%A, %d. %B %Y %I:%M%p\n"))
        out.flush()
        print 'Processing ' + str(total) + ' files...'

        for item in files:
            tempfilename = '.' + str(uuid.uuid4())

            if item['type'] is 'jpg':
                print 'Threading Optimization ' + str(count) + '/' + str(total) + ' (JPG)'
                processes.append({'process': subprocess.Popen([
	                    'guetzli',
	                    '--verbose',
	                    item['file'],
	                    tempfilename
	                ],
	                stdout=out,
	                stderr=out
                ), 'tempfilename': tempfilename, 'filename': item['file']})
            elif item['type'] is 'png':
                print 'Threading Optimization ' + str(count) + '/' + str(total) + ' (PNG)'
                processes.append({'process': subprocess.Popen([
	                    'zopflipng',
	                    '-m',
	                    item['file'],
	                    tempfilename
	                ],
                    stdout=out,
                    stderr=out
                ), 'tempfilename': tempfilename, 'filename': item['file']})
            count += 1

        while processes:
            for proc in processes:
                retcode = proc['process'].poll()
                if retcode is not None:
                    shutil.copy(proc['tempfilename'], proc['filename'])
                    os.remove(proc['tempfilename'])
                    processes.remove(proc)
                    print 'Thread ' + str(doneCount) + '/' + str(total) + ' Ended'
                    if doneCount == total:
                        print 'Processing Complete!'
                    doneCount += 1
                    break
                else:
                    time.sleep(.1)
                    continue

def check_file(item):
    '''Checks if a file is a JPG or PNG, and sorts them'''
    if os.path.isfile(item):
        if item.endswith(('.jpg', '.jpeg', '.JPG', '.JPEG')):
            files.append({'file': item, 'type': 'jpg'})
        elif item.endswith(('.png', '.PNG')):
            files.append({'file': item, 'type': 'png'})

def usage():
    '''Prints usage statement'''
    print 'goptim [-h] <PNG/JPG or Directory>[, <PNG/JPG or Directory>][, ...]'

if __name__ == "__main__":
    main()

以上是关于python 用于Google图像压缩实用程序zopflipng(PNG)和guetzli(JPG)的快速和脏的包装器。的主要内容,如果未能解决你的问题,请参考以下文章

python 用于压缩文件夹中所有图像的python脚本

用于扩展或增强 bq 命令行的 Google BigQuery bq 命令行 SDK

python Python中的图像Glitching实用程序

工科生实用链接(图像处理优化算法压缩深度学习)

Google 的 Page Speed 无损图像压缩是如何工作的?

图像压缩编码和解码原理——阐述了DCT变换的实质