4 from os.path import splitext, dirname, basename, realpath
5 from PIL import Image, ImageFilter, ImageEnhance, ImageOps
8 def resize(image, max_width, max_height):
9 """Resize image so it's not wider than max_width and not higher than max_height."""
10 width, height = image.size
11 ratio = max(1.0, float(width) / max_width, float(height) / max_height)
12 new_width, new_height = int(width / ratio), int(height / ratio)
13 return image.resize((new_width, new_height), Image.ANTIALIAS)
16 def crop(image, ratio, from_right=False):
17 """Crop image to ratio of current width."""
18 width, height = image.size
19 new_width = width * ratio
21 bounds = (int(width - new_width), 0, int(width), int(height))
23 bounds = (0, 0, int(new_width), int(height))
24 image = image.crop(bounds)
30 """Return width to height ratio of image."""
31 width, height = image.size
32 return float(width) / height
35 def try_creating(directory):
42 output_dir = realpath(os.getcwd()) + '/output'
43 big_output_dir = output_dir + '/big'
44 tmp_output_dir = output_dir + '/tmp'
46 try_creating(output_dir)
47 try_creating(big_output_dir)
48 try_creating(tmp_output_dir)
51 for file_name in sys.argv[1:]:
52 base_name, ext = splitext(file_name)
54 image = Image.open(file_name)
56 sys.stderr.write('\nerror:%s:%s\n' % (file_name, e.message))
61 images = [crop(image, 0.5), crop(image, 0.5, True)]
65 for i, image in enumerate(images):
66 image = image.filter(ImageFilter.SHARPEN)
68 image = image.filter(ImageFilter.MinFilter)
73 # image = image.point(convert)
74 image = ImageOps.autocontrast(image, cutoff=80)
75 image = image.convert('L')
76 image = image.filter(ImageFilter.SHARPEN)
78 image_name = '%s.%d.png' % (basename(base_name), i)
81 small_image = resize(image, 480, 720)
82 small_image.save(tmp_output_dir + '/' + image_name, optimize=True, bits=8)
83 os.system('pngnq -n 8 -e .png -d "%s" -f "%s"' % (
85 tmp_output_dir + '/' + image_name,
87 os.remove(tmp_output_dir + '/' + image_name)
89 big_image = resize(image, 960, 1440)
90 big_image.save(tmp_output_dir + '/' + image_name, optimize=True, bits=8)
91 os.system('pngnq -n 8 -e .png -d "%s" -f "%s"' % (
93 tmp_output_dir + '/' + image_name,
95 os.remove(tmp_output_dir + '/' + image_name)
99 os.remove(tmp_output_dir)