5 from os.path import splitext, dirname, basename, realpath
6 from PIL import Image, ImageFilter, ImageEnhance, ImageOps
9 def resize(image, max_width, max_height):
10 """Resize image so it's not wider than max_width and not higher than max_height."""
11 width, height = image.size
12 ratio = max(1.0, float(width) / max_width, float(height) / max_height)
13 new_width, new_height = int(width / ratio), int(height / ratio)
14 return image.resize((new_width, new_height), Image.ANTIALIAS)
17 def crop(image, ratio, from_right=False):
18 """Crop image to ratio of current width."""
19 width, height = image.size
20 new_width = width * ratio
22 bounds = (int(width - new_width), 0, int(width), int(height))
24 bounds = (0, 0, int(new_width), int(height))
25 image = image.crop(bounds)
31 """Return width to height ratio of image."""
32 width, height = image.size
33 return float(width) / height
36 def try_creating(directory):
43 output_dir = realpath(os.getcwd()) + '/output'
44 # big_output_dir = output_dir + '/big'
45 tmp_output_dir = output_dir + '/tmp'
47 try_creating(output_dir)
48 # try_creating(big_output_dir)
49 try_creating(tmp_output_dir)
52 for file_name in sys.argv[1:]:
53 base_name, ext = splitext(file_name)
55 image = Image.open(file_name)
57 sys.stderr.write('\nerror:%s:%s\n' % (file_name, e.message))
62 images = [crop(image, 0.6), crop(image, 0.6, from_right=True)]
66 for i, image in enumerate(images):
67 image_name = '%s.%d.png' % (basename(base_name), i)
70 small_image = resize(image, 640, 960)
71 small_image = small_image.convert('L')
72 small_image = ImageOps.autocontrast(small_image, cutoff=85)
73 # small_image = small_image.filter(ImageFilter.SHARPEN)
74 small_image.save(tmp_output_dir + '/' + image_name)
76 os.system('pngnq -n 128 -s 1 -e .png -d "%s" -f "%s"' % (
78 tmp_output_dir + '/' + image_name,
80 os.remove(tmp_output_dir + '/' + image_name)
82 # big_image = resize(image, 960, 1440)
83 # big_image = big_image.convert('L')
84 # big_image = big_image.filter(ImageFilter.SHARPEN)
85 # big_image.save(tmp_output_dir + '/' + image_name, optimize=True)
86 # os.system('pngnq -n 16 -s 1 -e .png -d "%s" -f "%s"' % (
88 # tmp_output_dir + '/' + image_name,
90 # os.remove(tmp_output_dir + '/' + image_name)
94 shutil.rmtree(tmp_output_dir)