Skip to content

Instantly share code, notes, and snippets.

@notlion
Last active February 28, 2018 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save notlion/f1847a5fc181cc5790db2eedf38f99c6 to your computer and use it in GitHub Desktop.
Save notlion/f1847a5fc181cc5790db2eedf38f99c6 to your computer and use it in GitHub Desktop.
Generates resized images at various resolutions
#!/usr/bin/env python
from __future__ import print_function
import os
import subprocess
from glob import glob
from wand.image import Image
ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
MEDIA_RESIZED_PATH = os.path.join(ROOT_PATH, 'media/resized')
MEDIA_PATH = os.path.join(ROOT_PATH, 'media')
MEDIA_GLOB = os.path.join(MEDIA_PATH, '**', '*.*')
RESIZE_WIDTHS = [720] #[360, 720, 2048]
LOG_VERBOSE = False
def make_resized_path(basepath, width, ext, suffix=''):
return '%s_%dw%s%s' % (basepath, width, suffix, ext)
def subproc_or_die(args):
if LOG_VERBOSE:
print('\n' + ' '.join(args))
subprocess.check_call(args)
def subproc(args):
if LOG_VERBOSE:
print('\n' + ' '.join(args))
return subprocess.call(args)
for path in glob(MEDIA_GLOB):
rootpath, ext = os.path.splitext(path)
resized_base = os.path.join(MEDIA_RESIZED_PATH, os.path.relpath(rootpath, MEDIA_PATH))
try:
os.makedirs(os.path.dirname(resized_base))
except OSError:
pass
if ext == '.png' or ext == '.jpg':
img = None
for width in RESIZE_WIDTHS:
img_resized_filename = make_resized_path(resized_base, width, ext)
if not os.path.exists(img_resized_filename):
print('Generating %s' % img_resized_filename)
# Lazy load images
if img is None:
img = Image(filename=path)
with img.clone() as img_resized:
if img.width > width:
img_resized.resize(width=width,
height=int(width * (float(img.height) / float(img.width))),
filter='lanczossharp')
if ext == '.png':
img_resized.format = 'png'
img_resized.strip()
img_resized.save(filename=img_resized_filename)
verbose_flag = '-v' if LOG_VERBOSE else '-q'
# Attempt to compress PNG images with pngnq and pngcrush
img_nq_filename = make_resized_path(resized_base, width, ext, '_quant')
if 99 == subproc(['pngquant', verbose_flag, '-f', '-Q 10-90', '--ext', '_quant.png', img_resized_filename]):
print('!!! Quantized PNG quality too low. Using original.')
os.rename(img_resized_filename, img_nq_filename)
else:
os.remove(img_resized_filename)
subproc_or_die(['pngcrush', verbose_flag, '-rem alla', '-rem text', img_nq_filename, img_resized_filename])
os.remove(img_nq_filename)
elif ext == '.jpg':
img_resized.format = 'pjpeg'
img_resized.compression = 'jpeg'
img_resized.compression_quality = 85
img_resized.strip()
img_resized.save(filename=img_resized_filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment