-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy paththumbnail_maker.py
76 lines (59 loc) · 2.74 KB
/
thumbnail_maker.py
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
75
76
# thumbnail_maker.py
import time
import os
import logging
from urllib.parse import urlparse
from urllib.request import urlretrieve
import PIL
from PIL import Image
logging.basicConfig(filename='logfile.log', level=logging.DEBUG)
class ThumbnailMakerService(object):
def __init__(self, home_dir='.'):
self.home_dir = home_dir
self.input_dir = self.home_dir + os.path.sep + 'incoming'
self.output_dir = self.home_dir + os.path.sep + 'outgoing'
def download_images(self, img_url_list):
# validate inputs
if not img_url_list:
return
os.makedirs(self.input_dir, exist_ok=True)
logging.info("beginning image downloads")
start = time.perf_counter()
for url in img_url_list:
# download each image and save to the input dir
img_filename = urlparse(url).path.split('/')[-1]
urlretrieve(url, self.input_dir + os.path.sep + img_filename)
end = time.perf_counter()
logging.info("downloaded {} images in {} seconds".format(len(img_url_list), end - start))
def perform_resizing(self):
# validate inputs
if not os.listdir(self.input_dir):
return
os.makedirs(self.output_dir, exist_ok=True)
logging.info("beginning image resizing")
target_sizes = [32, 64, 200]
num_images = len(os.listdir(self.input_dir))
start = time.perf_counter()
for filename in os.listdir(self.input_dir):
orig_img = Image.open(self.input_dir + os.path.sep + filename)
for basewidth in target_sizes:
img = orig_img
# calculate target height of the resized image to maintain the aspect ratio
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
# perform resizing
img = img.resize((basewidth, hsize), PIL.Image.LANCZOS)
# save the resized image to the output dir with a modified file name
new_filename = os.path.splitext(filename)[0] + \
'_' + str(basewidth) + os.path.splitext(filename)[1]
img.save(self.output_dir + os.path.sep + new_filename)
os.remove(self.input_dir + os.path.sep + filename)
end = time.perf_counter()
logging.info("created {} thumbnails in {} seconds".format(num_images, end - start))
def make_thumbnails(self, img_url_list):
logging.info("START make_thumbnails")
start = time.perf_counter()
self.download_images(img_url_list)
self.perform_resizing()
end = time.perf_counter()
logging.info("END make_thumbnails in {} seconds".format(end - start))