CustomUploadAndFilters: imaging.py

File imaging.py, 1.7 KB (added by Enrico <rico.bl@…>, 18 years ago)

Image maniupulation utilities for custom upload fields

Line 
1import Image
2
3def fit(file_path, max_width=None, max_height=None, save_as=None):
4 # Open file
5 img = Image.open(file_path)
6
7 # Store original image width and height
8 w, h = img.size
9
10 # Replace width and height by the maximum values
11 w = int(max_width or w)
12 h = int(max_height or h)
13
14 # Proportinally resize
15 img.thumbnail((w, h), Image.ANTIALIAS)
16
17 # Save in (optional) 'save_as' or in the original path
18 img.save(save_as or file_path)
19
20 return True
21
22# def fit
23
24def fit_crop(file_path, max_width=None, max_height=None, save_as=None):
25 # Open file
26 img = Image.open(file_path)
27
28 # Store original image width and height
29 w, h = float(img.size[0]), float(img.size[1])
30
31 # Use the original size if no size given
32 max_width = float(max_width or w)
33 max_height = float(max_height or h)
34
35 # Find the closest bigger proportion to the maximum size
36 scale = max(max_width / w, max_height / h)
37
38 # Image bigger than maximum size?
39 if (scale < 1):
40 # Calculate proportions and resize
41 w = int(w * scale)
42 h = int(h * scale)
43 img = img.resize((w, h), Image.ANTIALIAS)
44 #
45
46 # Avoid enlarging the image
47 max_width = min(max_width, w)
48 max_height = min(max_height, h)
49
50 # Define the cropping box
51 left = int((w - max_width) / 2)
52 top = int((h - max_height) / 2)
53 right = int(left + max_width)
54 bottom = int(top + max_height)
55
56 # Crop to fit the desired size
57 img = img.crop( (left, top, right, bottom) )
58
59 # Save in (optional) 'save_as' or in the original path
60 img.save(save_as or file_path)
61
62 return True
63
64# def fit_crop
Back to Top