Skip to content

Instantly share code, notes, and snippets.

@rudyryk
Created December 23, 2014 10:30
Show Gist options
  • Save rudyryk/385c0aee7d1707a42aea to your computer and use it in GitHub Desktop.
Save rudyryk/385c0aee7d1707a42aea to your computer and use it in GitHub Desktop.
Create retina @2x and non-retina resized images from @3x sized images
#!/usr/bin/env python
import os
import sys
print(sys.executable)
def resize_images_in_path(path, out_dir, imagemagic=False):
"""Build 2x and 1x downsized images by 3x images in directory."""
dirs = os.listdir(path)
assert (out_dir and os.path.realpath(path) != os.path.realpath(out_dir)), (
"Error, output dir and input dir must be different!")
if out_dir:
try:
os.makedirs(out_dir)
except OSError:
pass
for item in dirs:
full_path = os.path.join(path, item)
file_name, ext = os.path.splitext(item)
if not os.path.isfile(full_path):
continue
if not ext in ('.png', '.jpg'):
continue
# if not file_name.endswith('@3x'):
# continue
if imagemagic:
make_resizes_from_3x_wand(full_path, out_dir=out_dir)
else:
make_resizes_from_3x_pillow(full_path, out_dir=out_dir)
def make_resizes_from_3x_wand(path, out_dir=None):
"""Make images resizes with Wand + ImageMagic."""
from wand.image import Image
file_name, ext = os.path.splitext(path)
with Image(filename=path) as im:
# 3x
file_3x = get_out_filepath(path, suffix='@3x', out_dir=out_dir)
im.save(filename=file_3x)
# 2x
size_2x = (int(im.size[0] * 2/3), int(im.size[1] * 2/3))
file_2x = get_out_filepath(path, suffix='@2x', out_dir=out_dir)
im.resize(*size_2x)
im.save(filename=file_2x)
# 1x
size_1x = (im.size[0] * 1/2, im.size[1] * 1/2)
file_1x = get_out_filepath(path, suffix='', out_dir=out_dir)
im.resize(*size_1x)
im.save(filename=file_1x)
def get_out_filepath(path, suffix='', out_dir=None):
"""Get output file path with scheme [output dir]/[base name][suffix].[ext]"""
if not out_dir:
out_dir = os.path.dirname(path)
file_name = os.path.basename(path)
base, ext = os.path.splitext(file_name)
return os.path.join(out_dir, base + suffix + ext)
def make_resizes_from_3x_pillow(path, out_dir=None):
"""Make images resizes with Pillow."""
from PIL import Image
file_name, ext = os.path.splitext(path)
im = Image.open(path)
# 3x
file_3x = get_out_filepath(path, suffix='@3x', out_dir=out_dir)
im.save(file_3x, optimize=True)
# 2x
size_2x = (im.size[0] * 2/3, im.size[1] * 2/3)
file_2x = get_out_filepath(path, suffix='@2x', out_dir=out_dir)
im_2x = im.resize(size_2x, Image.ANTIALIAS)
im_2x.save(file_2x, optimize=True)
# 1x
size_1x = (im.size[0] * 1/3, im.size[1] * 1/3)
file_1x = get_out_filepath(path, suffix='', out_dir=out_dir)
im_1x = im.resize(size_1x, Image.ANTIALIAS)
im_1x.save(file_1x, optimize=True)
if __name__ == '__main__':
out_dir = os.path.join(os.getcwd(), 'Build')
resize_images_in_path(os.getcwd(), out_dir=out_dir, imagemagic=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment