Skip to content

Instantly share code, notes, and snippets.

@cupof-github
Last active May 8, 2017 05:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cupof-github/c9db630225a260832cccf7107f0adf95 to your computer and use it in GitHub Desktop.
Save cupof-github/c9db630225a260832cccf7107f0adf95 to your computer and use it in GitHub Desktop.
Guetzli wrapper for Python
import os
import sys
class GuentzliWrapper:
""" This Class is wrapper for the guentzli, google develped.
You can encode multiple (jpeg || png) file via guentzli on CLI.
( Tested: Python 3.6, 2.7.13, pypy 5.7.0)
Put this file anywhere. And put this file of path to .bashrc or .zshrc
and then ...
# to .bashrc or .zshrc * any command name you want
alias myguent='python /YOUR/PATH/guetzli.py '
then souce ~/.bashrc OR ~/.zshrc
# usage
$ myguent myimg.jpeg
or multiple images..
$ myguent myimg1.jpeg myimg2.jpeg myimg3.jpeg
"""
def __init__(self):
self.dir = os.getcwd() + '/'
self.inputs = sys.argv
self.color = {
'green': '\033[92m',
'red': '\033[91m',
'blue': '\033[94m',
'end': '\033[0m'
}
del self.inputs[0] # remove self-file-name
pass
def _check_File_Type(self):
for x in self.inputs:
if not x.endswith((".jpeg", ".jpg", ".png")):
print(self.color["red"] + x +
' is invalid extention' + self.color["end"])
return False
pass
def _check_File_Exists(self):
try:
if len(self.inputs) is 0:
raise Exception("Error: none-argument")
if self._check_File_Type() is False:
raise Exception("Error: invalid file-type")
array = list()
for x in self.inputs:
if os.path.exists(self.dir + x) is False:
raise Exception("File: " + self.dir + x + " is not exist")
else:
array.append(x)
pass
return list(set(array)) # remove element if contains duplicated
except Exception as e:
print(self.color["red"] + e + self.color["end"])
return sys.exit()
pass
pass
def _percentage(self, before, after):
return round(100 - (float(after) / before * 100), 2)
pass
def execute(self):
for x in self._check_File_Exists():
before = os.path.getsize(x)
print("PROGRESS: " + x)
# execute guetzli command
os.system("guetzli {0} {1}".format(
self.dir + x,
self.dir + x.replace('.png', '.jpeg'))
)
if x.endswith('.png') is True:
# if file is .png
print(self.color["green"] + "Created JPEG image : {0} \033[0m \n"
.format(x.replace('.png', '.jpeg')))
else:
after = os.path.getsize(x)
print(self.color["green"] + "{0} byte -> {1} byte ( {2}% reduced ) \033[0m \n"
.format(before, after, self._percentage(before, after)))
print(self.color["blue"] + "Completed !!" + self.color['end'])
pass
if __name__ == "__main__":
x = GuentzliWrapper()
x.execute()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment