-
Notifications
You must be signed in to change notification settings - Fork 7
/
generate_rotated_images.py
executable file
·70 lines (53 loc) · 1.94 KB
/
generate_rotated_images.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
#!/usr/bin/env python
'''Generates rotated versions of static images.
This winds up being way simpler than trying to apply the rotations in the
client's browser.
Input: data.json
Output: rotated-assets/{thumb,600px}/*.jpg
This won't overwrite existing files (i.e. it's incremental).
'''
import json
import os
import sys
import time
import requests
import shutil
from PIL import Image
def download(url, destination_path):
response = requests.get(url, stream=True)
with open(destination_path, 'wb') as out_file:
shutil.copyfileobj(response.raw, out_file)
def image_path(photo_id, degrees, is_thumb):
return 'rotated-assets/%s/%s.%s.jpg' % (
'thumb' if is_thumb else '600px',
photo_id, degrees)
def image_url(photo_id, is_thumb):
return 'http://oldnyc-assets.nypl.org/%s/%s.jpg' % (
'thumb' if is_thumb else '600px', photo_id)
work = [] # (photo_id, degrees) tuples
for photo in json.load(open('data.json'))['photos']:
degrees = photo.get('rotation')
if not degrees:
continue
photo_id = photo['photo_id']
if not os.path.exists(image_path(photo_id, degrees, is_thumb=False)):
work.append((photo_id, degrees))
print('Will generate %d rotated images and thumbnails' % len(work))
for photo_id, degrees in work:
for is_thumb in (False, True):
temp_dest = '/tmp/%s.jpg' % photo_id
final_dest = image_path(photo_id, degrees, is_thumb)
url = image_url(photo_id, is_thumb)
sys.stderr.write('Fetching %s --> %s\n' % (url, final_dest))
download(url, temp_dest)
im = Image.open(open(temp_dest, 'rb'))
if degrees == 90:
im = im.transpose(Image.ROTATE_270)
elif degrees == 180:
im = im.transpose(Image.ROTATE_180)
elif degrees == 270:
im = im.transpose(Image.ROTATE_90)
else:
raise ValueError('Invalid rotation: %d' % degrees)
im.save(final_dest)
time.sleep(1)