Workout With Friends Stay fit with a little motivation

- Main Page
- Namespaces
- Classes
- Files

- File List
- File Members

All Classes Namespaces Files Functions Variables Properties
image.py
Go to the documentation of this file.
1 ##
2 #
3 # Image manipulation helper functions.
4 #
5
6 import os
7 import shutil
8 from PIL import Image, ImageOps
9 from pyramid.asset import abspath_from_asset_spec
10
11
12 ##
13 #
14 # Create a thumbnail copy of the given image file.
15 #
16 # @param infile Source image file
17 # @param outpath Destination path of the thumbnail
18 # @param size Thumbnail dimensions
19 #
20 def make_thumbnail(infile, outpath, size):
21 infile.seek(0)
22 outpath = abspath_from_asset_spec(outpath)
23 if isinstance(size, int):
24 size = (size, size)
25 image = Image.open(infile)
26 if image.mode not in ('L', 'RGB'):
27 image = image.convert('RGB')
28 image = ImageOps.fit(image, size, Image.ANTIALIAS)
29 image.save(outpath, quality=100)
30
31
32 ##
33 #
34 # Upload the original image file, and create the necessary thumbnail versions.
35 #
36 # @param versions Dictionary of key => dimensions
37 #
38 def upload_and_make_thumbnails(infile, upload_dir, filename, versions=None):
39 filepath = os.path.join(upload_dir, filename)
40 if os.path.exists(filepath):
41 os.remove(filepath)
42 shutil.copyfileobj(infile, open(filepath, 'wb'))
43 if versions:
44 for subdir, size in versions.items():
45 filepath = os.path.join(upload_dir, subdir, filename)
46 make_thumbnail(infile, filepath, size)
47
48
49 ##
50 #
51 # Utility class for thumbnailed images, used to access both the original
52 # as well as all thubnail versions of the image.
53 #
54 class StoredImage(unicode):
55
56 def __new__(self, root_dir, filename, versions=None):
57 self.root_dir = root_dir
58 self.filename = filename
59 self.versions = versions
60 return unicode.__new__(self, os.path.join(root_dir, filename))
61
62 def __getattr__(self, name):
63 if name not in self.versions:
64 raise AttributeError('Image does not have a %s version' % name)
65 return os.path.join(self.root_dir, name, self.filename)
66