-
Notifications
You must be signed in to change notification settings - Fork 844
/
Copy pathoptimize_images.py
61 lines (47 loc) · 1.78 KB
/
optimize_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
# -*- coding: utf-8 -*-
"""
Optimized images (jpg and png)
Assumes that jpegtran and optipng are isntalled on path.
http://jpegclub.org/jpegtran/
http://optipng.sourceforge.net/
Copyright (c) 2012 Irfan Ahmad (http://i.com.pk)
"""
import logging
import os
from subprocess import call
from pelican import signals
logger = logging.getLogger(__name__)
# Display command output on DEBUG and TRACE
SHOW_OUTPUT = logger.getEffectiveLevel() <= logging.DEBUG
# A list of file types with their respective commands
COMMANDS = {
# '.ext': ('command {flags} {filename', 'silent_flag', 'verbose_flag')
'.svg': ('svgo {flags} --input="{filename}" --output="{filename}"', '--quiet', ''),
'.jpg': ('jpegtran {flags} -copy none -optimize -progressive -outfile "{filename}" "{filename}"', '', '-v'),
'.png': ('optipng {flags} "{filename}"', '--quiet', ''),
}
def optimize_images(pelican):
"""
Optimized jpg and png images
:param pelican: The Pelican instance
"""
for dirpath, _, filenames in os.walk(pelican.settings['OUTPUT_PATH']):
for name in filenames:
if os.path.splitext(name)[1] in COMMANDS.keys():
optimize(dirpath, name)
def optimize(dirpath, filename):
"""
Check if the name is a type of file that should be optimized.
And optimizes it if required.
:param dirpath: Path of the file to be optimzed
:param name: A file name to be optimized
"""
filepath = os.path.join(dirpath, filename)
logger.info('optimizing %s', filepath)
ext = os.path.splitext(filename)[1]
command, silent, verbose = COMMANDS[ext]
flags = verbose if SHOW_OUTPUT else silent
command = command.format(filename=filepath, flags=flags)
call(command, shell=True)
def register():
signals.finalized.connect(optimize_images)