import socket try from PIL import Image except ImportError import Imag

 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import socket
try:
from PIL import Image
except ImportError:
import Image
from StringIO import StringIO
import logging
import time
import random
import os.path
import urllib
from settings import settings
def random_name():
"""
Generate random file name.
"""
a = str(time.time()).replace('.', '')
b = str(random.random()).replace('.', '')
return a + b
def make_thumbnail(img, size):
"""
Generate random file path and the corresponding URI.
@param size: tuple with width and height
"""
fname = random_name() + '.jpg'
fname = os.path.join(settings.THUMBNAIL_DIR, fname)
uri = fname[len(settings.STATIC_ROOT):]
dup = img.copy()
dup.thumbnail(size, Image.ANTIALIAS)
dup.save(fname, "JPEG")
return uri
def process_photos(urls):
"""
Download photos, make thumnails.
"""
old_timeout = socket.getdefaulttimeout()
socket.setdefaulttimeout(5)
photos = []
for url in urls:
try:
data = urllib.urlopen(url).read()
except IOError, ex:
logging.debug(ex)
continue
try:
img = Image.open(StringIO(data))
except IOError, ex:
logging.debug(ex)
continue
thumb_uri = make_thumbnail(img, (100, 100))
small_uri = make_thumbnail(img, (240, 240))
photo = {'id': None, 'photo_page_url': url,
'small_size_url': small_uri,
'thumbnail': thumb_uri}
photos.append(photo)
return photos