0
|
1 #!/usr/bin/env python
|
|
2
|
|
3 import os
|
|
4
|
|
5 from PIL import Image
|
|
6
|
|
7 def crop_resize(image, size):
|
|
8 """crop out the proportional middle of the image and set to the desired size"""
|
|
9 assert size[0] or size[1]
|
|
10
|
|
11 size = list(size)
|
|
12
|
|
13 if size[0] > image.size[0]:
|
|
14 return image
|
|
15 if size[1] > image.size[1]:
|
|
16 return image
|
|
17
|
|
18 image_ar = image.size[0]/float(image.size[1])
|
|
19 crop = not size[0] or not size[1]
|
|
20 if not size[1]:
|
|
21 size[1] = int(image.size[1]*size[0]/float(image.size[0]) )
|
|
22 if not size[0]:
|
|
23 size[0] = int(image.size[0]*size[1]/float(image.size[1]) )
|
|
24 size_ar = size[0]/float(size[1])
|
|
25
|
|
26 if crop:
|
|
27 if image_ar > size_ar:
|
|
28 # trim the width
|
|
29 xoffset = int(0.5*(image.size[0] - size_ar*image.size[1]))
|
|
30 image = image.crop((xoffset, 0, image.size[0]-xoffset, image.size[1]))
|
|
31 elif image_ar < size_ar:
|
|
32 # trim the height
|
|
33 yoffset = int(0.5*(image.size[1] - image.size[0]/size_ar))
|
|
34 image = image.crop((0, yoffset, image.size[0], image.size[1] - yoffset))
|
|
35
|
|
36 return image.resize(size, Image.ANTIALIAS)
|
|
37
|
|
38 if __name__ == '__main__':
|
|
39 from optparse import OptionParser
|
|
40 parser = OptionParser()
|
|
41 parser.add_option('-f', '--file')
|
|
42 parser.add_option('-W', '--width')
|
|
43 parser.add_option('-H', '--height')
|
|
44 (options, args) = parser.parse_args()
|
|
45
|
|
46 assert os.path.exists(options.file)
|
|
47
|
|
48 i = Image.open(options.file)
|
|
49 new_image = crop_resize(i, (int(options.width), int(options.height)))
|
|
50 new_image.show()
|