import os path import sys from StringIO import StringIO from datetime

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import os.path
import sys
from StringIO import StringIO
from datetime import datetime, timedelta
import logging
try:
import Image
except ImportError:
from PIL import Image
def rawdata_from_image(img):
"""
Convert PIL Image instance to raw data.
"""
string = StringIO()
img.save(string,format=img.format)
return string.getvalue()
def image_from_rawdata(rawdata):
"""
Convert raw data to PIL Image.
"""
return Image.open(StringIO(rawdata))
def resize_image(width, height, image=None, rawdata=None):
"""
Resize image to fit it into (width, height) box.
If rawdata is not None than make image from it, process it
and return rawdata.
"""
if rawdata:
image = image_from_rawdata(rawdata)
try:
image.thumbnail((width, height),resample=Image.ANTIALIAS)
except Exception, err:
logging.error(err)
return None
if rawdata:
return rawdata_from_image(image)
else:
return image