Skip to content

Instantly share code, notes, and snippets.

@slowkow
Last active November 21, 2022 23:04
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save slowkow/d0cfa4c21ca7e72f6fed4a1d82112b94 to your computer and use it in GitHub Desktop.
Save slowkow/d0cfa4c21ca7e72f6fed4a1d82112b94 to your computer and use it in GitHub Desktop.
Optimize base64 encoded PNG images in an HTML file.
#!/usr/bin/env python
"""
optimize_html.py
Kamil Slowikowski
November 14, 2016
Optimize base64 encoded PNG images in an HTML file.
USAGE
python optimize_html.py infile.html
Output will be written to 'infile-optimized.html'
LICENSE
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
"""
import argparse
import re
import base64
import subprocess
import sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument('html_file', type=argparse.FileType('r'))
args = parser.parse_args()
# Read the HTML.
html_string = args.html_file.read()
# Optimize all of the PNG images with pngquant.
opt_string = re.sub('<img src="([^"]+)"', replace_img_src, html_string)
# Write the optimized HTML.
out_file = re.sub('\.html', '-optimized.html', args.html_file.name)
with open(out_file, 'wb') as out:
out.write(opt_string)
def replace_img_src(match):
src_string = match.group(1)
return '<img src="' + optimize(src_string) + '"'
def optimize(src_string):
"""
Take a base64 data string like:
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABIAAAAMACAYAAA'
Use pngquant to optimize the image data.
Return a bas64 data string with the optimized image data.
"""
key = 'data:image/png;base64,'
# Only PNG is implemented.
if not src_string.startswith(key):
return src_string
i = len(key)
raw_data = base64.decodestring(src_string[i:])
# filename = src_string[i:i+16] + '.png'
# with open(filename, 'wb') as out:
# out.write(raw_data)
proc = subprocess.Popen(
'pngquant --speed 1 --quality 0-60 -'.split(),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE
)
opt_data = proc.communicate(raw_data)[0]
# filename = src_string[i:i+16] + '-optimized.png'
# with open(filename, 'wb') as out:
# out.write(opt_data)
opt_string = src_string[:i] + base64.encodestring(opt_data)
# sys.stderr.write('Before optimization: {}\n'.format(len(src_string)))
# sys.stderr.write('After optimization: {}\n'.format(len(opt_string)))
return opt_string
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment