Usunięcie modelu Book z admina.
[redakcja.git] / imgconv.py
1 #!/usr/bin/env python
2 import sys
3 import os
4 from os.path import splitext, dirname
5 from PIL import Image, ImageFilter, ImageEnhance, ImageOps
6
7
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)
14
15
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
20     if from_right:
21         bounds = (int(width - new_width), 0, int(width), int(height))
22     else:
23         bounds = (0, 0, int(new_width), int(height))
24     image = image.crop(bounds)
25     image.load()
26     return image
27
28
29 def ratio(image):
30     """Return width to height ratio of image."""
31     width, height = image.size
32     return float(width) / height
33     
34     
35 for file_name in sys.argv[1:]:
36     try:
37         os.mkdir('output')
38     except:
39         pass
40     base_name, ext = splitext(file_name)
41     try:
42         image = Image.open(file_name)
43     except IOError, e:
44         sys.stderr.write('\nerror:%s:%s\n' % (file_name, e.message))
45         continue
46     
47     # Check ratio
48     if ratio(image) > 1:
49         images = [crop(image, 0.5), crop(image, 0.5, True)]
50     else:
51         images = [image]
52     
53     for i, image in enumerate(images):
54         image = image.filter(ImageFilter.SHARPEN)
55         
56         image = image.filter(ImageFilter.MinFilter)
57         def convert(i):
58             if i > 48:
59                 return 255
60             return i
61         image = image.point(convert)
62         image = ImageOps.autocontrast(image, cutoff=95)
63         image = image.convert('L')
64         image = image.filter(ImageFilter.SHARPEN)
65         
66         # Save files
67         small_image = resize(image, 480, 720)
68         small_image_file_name = '%s.small.%d.png' % (base_name, i)
69         small_image.save(small_image_file_name, optimize=True, bits=6)
70         os.system('pngnq -n 8 -e .png -d output -f "%s"' % small_image_file_name)
71         os.remove(small_image_file_name)
72         
73         big_image = resize(image, 960, 1440)
74         big_image_file_name = '%s.big.%d.png' % (base_name, i)
75         big_image.save(big_image_file_name, optimize=True, bits=6)
76         os.system('pngnq -n 8 -e .png -d output -f "%s"' % big_image_file_name)
77         os.remove(big_image_file_name)
78         
79     sys.stderr.write('.')