8000 added image optimizer · realpython/python-scripts@75f1eb4 · GitHub
[go: up one dir, main page]

Skip to content

Commit 75f1eb4

Browse files
committed
added image optimizer
1 parent 53da94f commit 75f1eb4

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

09_basic_link_web_crawler.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@ def crawl(url):
2626
link = urlparse.urljoin(url, link)
2727

2828
print link
29-
29+
3030

3131
if __name__ == '__main__':
3232
crawl('http://www.realpython.com')
33+

11_optimize_images_with_wand.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import fnmatch
2+
import os
3+
4+
# sudo pip install Wand
5+
from wand.image import Image
6+
# sudo pip install http://pypi.python.org/packages/source/h/hurry.filesize/hurry.filesize-0.9.tar.gz
7+
from hurry.filesize import size
8+
9+
10+
# constants
11+
PATH = '/../../../..'
12+
PATTERN = '*.jpg'
13+
14+
15+
def get_image_file_names(filepath, pattern):
16+
matches = []
17+
if os.path.exists(filepath):
18+
for root, dirnames, filenames in os.walk(filepath):
19+
for filename in fnmatch.filter(filenames, pattern):
20+
matches.append(os.path.join(root, filename)) # full path
21+
if matches:
22+
print "Found {} files, with a total file size of {}.".format(len(matches), get_total_size(matches))
23+
return matches
24+
else:
25+
print "No files found."
26+
else:
27+
print "Sorry that path does not exist. Try again."
28+
29+
30+
def get_total_size(list_of_image_names):
31+
total_size = 0
32+
for image_name in list_of_image_names:
33+
total_size += os.path.getsize(image_name)
34+
return size(total_size)
35+
36+
37+
def resize_images(list_of_image_names):
38+
print "Optimizing ... "
39+
for index, image_name in enumerate(list_of_image_names):
40+
with open(image_name) as f:
41+
image_binary = f.read()
42+
with Image(blob=image_binary) as img:
43+
if img.height >= 600:
44+
img.transform(resize='x600')
45+
img.save(filename=image_name)
46+
print "Optimization complete."
47+
48+
49+
if __name__ == '__main__':
50+
all_images = get_image_file_names(PATH, PATTERN)
51+
resize_images(all_images)
52+
get_image_file_names(PATH, PATTERN)

0 commit comments

Comments
 (0)
0