2 # -*- coding: utf-8 -*-
4 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
5 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
10 from os.path import splitext, dirname, basename, realpath
11 from PIL import Image, ImageFilter, ImageEnhance, ImageOps
14 def resize(image, max_width, max_height):
15 """Resize image so it's not wider than max_width and not higher than max_height."""
16 width, height = image.size
17 ratio = max(1.0, float(width) / max_width, float(height) / max_height)
18 new_width, new_height = int(width / ratio), int(height / ratio)
19 return image.resize((new_width, new_height), Image.ANTIALIAS)
22 def crop(image, ratio, from_right=False):
23 """Crop image to ratio of current width."""
24 width, height = image.size
25 new_width = width * ratio
27 bounds = (int(width - new_width), 0, int(width), int(height))
29 bounds = (0, 0, int(new_width), int(height))
30 image = image.crop(bounds)
36 """Return width to height ratio of image."""
37 width, height = image.size
38 return float(width) / height
41 def try_creating(directory):
48 output_dir = realpath(os.getcwd()) + '/output'
49 # big_output_dir = output_dir + '/big'
50 tmp_output_dir = output_dir + '/tmp'
52 try_creating(output_dir)
53 # try_creating(big_output_dir)
54 try_creating(tmp_output_dir)
57 for file_name in sys.argv[1:]:
58 base_name, ext = splitext(file_name)
60 image = Image.open(file_name)
62 sys.stderr.write('\nerror:%s:%s\n' % (file_name, e.message))
67 images = [crop(image, 0.6), crop(image, 0.6, from_right=True)]
71 for i, image in enumerate(images):
72 image_name = '%s.%d.png' % (basename(base_name), i)
75 small_image = resize(image, 640, 960)
76 small_image = small_image.convert('L')
77 small_image = ImageOps.autocontrast(small_image, cutoff=85)
78 # small_image = small_image.filter(ImageFilter.SHARPEN)
79 small_image.save(tmp_output_dir + '/' + image_name)
81 os.system('pngnq -n 128 -s 1 -e .png -d "%s" -f "%s"' % (
83 tmp_output_dir + '/' + image_name,
85 os.remove(tmp_output_dir + '/' + image_name)
87 # big_image = resize(image, 960, 1440)
88 # big_image = big_image.convert('L')
89 # big_image = big_image.filter(ImageFilter.SHARPEN)
90 # big_image.save(tmp_output_dir + '/' + image_name, optimize=True)
91 # os.system('pngnq -n 16 -s 1 -e .png -d "%s" -f "%s"' % (
93 # tmp_output_dir + '/' + image_name,
95 # os.remove(tmp_output_dir + '/' + image_name)
99 shutil.rmtree(tmp_output_dir)