Permalink
Browse files

Added options:

  --min-percent=INT      Minimum percent of optimisation to warn about
  --save-optimized=DIR   Directory to save optimised files
  • Loading branch information...
1 parent a56b11c commit be6a23f3c00484b102e88ecaeebea2d7c5025b7d Marat Dyatko committed Jul 9, 2012
Showing with 51 additions and 22 deletions.
  1. +26 −9 smush/optimiser/optimiser.py
  2. +25 −13 smush/smush.py
@@ -27,6 +27,8 @@ def __init__(self, **kwargs):
self.files_optimised = 0
self.bytes_saved = 0
self.list_only = kwargs.get('list_only')
+ self.min_percent = kwargs.get('min_percent')
+ self.save_optimized = kwargs.get('save_optimized')
self.array_optimised_file = []
self.quiet = kwargs.get('quiet')
self.stdout = Scratch()
@@ -102,7 +104,7 @@ def _is_acceptable_image(self, input):
return output.startswith(self.format)
- def optimise(self):
+ def optimise(self, original_dir):
"""
Calls the 'optimise_image' method on the object. Tests the 'optimised' file size. If the
generated file is larger than the original file, discard it, otherwise discard the input file.
@@ -139,7 +141,17 @@ def optimise(self):
self._keep_smallest_file(self.input, output_file_name)
else:
if self.list_only == True:
- self._list_only(self.input, output_file_name)
+ is_optimised = self._list_only(self.input, output_file_name)
+ if self.save_optimized and is_optimised:
+ optimized_path = os.path.join(os.path.abspath(self.save_optimized), os.path.relpath(self.input, original_dir))
+ optimized_dir = os.path.dirname(optimized_path)
+
+ if not os.path.exists(optimized_dir):
+ os.makedirs(optimized_dir)
+
+ logging.info("Saving optimised image to %s" % (optimized_path))
+ shutil.copyfile(output_file_name, optimized_path)
+
if os.path.isfile(output_file_name):
os.unlink(output_file_name)
break
@@ -155,16 +167,21 @@ def _list_only(self, input, output):
if (output_size > 0 and output_size < input_size):
bytes_saved = (input_size - output_size)
+ bytes_saved_percent = int(100 - round((output_size / float(input_size)) * 100))
self.files_optimised += 1
self.bytes_saved += bytes_saved
- self.array_optimised_file.append({
- 'name': input,
- 'input_size': input_size,
- 'output_size': output_size,
- 'bytes_saved': bytes_saved,
- 'bytes_saved_percent': int(100 - round((output_size / float(input_size)) * 100)),
- })
+ if bytes_saved_percent > self.min_percent:
+ self.array_optimised_file.append({
+ 'name': input,
+ 'input_size': input_size,
+ 'output_size': output_size,
+ 'bytes_saved': bytes_saved,
+ 'bytes_saved_percent': bytes_saved_percent,
+ })
+
+ return True
+ return False
def _keep_smallest_file(self, input, output):
"""
View
@@ -1,6 +1,6 @@
#!/usr/bin/env python
-import sys, os, os.path, getopt, time, shlex, subprocess, logging
+import sys, os, os.path, getopt, time, shlex, subprocess, logging, shutil
from subprocess import CalledProcessError
from optimiser.formats.png import OptimisePNG
from optimiser.formats.jpg import OptimiseJPG
@@ -51,13 +51,14 @@ def __smush(self, file):
logging.info('optimising file %s' % (file))
self.__files_scanned += 1
self.optimisers[key].set_input(file)
- self.optimisers[key].optimise()
+ self.optimisers[key].optimise(self.original_dir)
def process(self, dir, recursive):
"""
Iterates through the input directory optimising files
"""
+ self.original_dir = dir
if recursive:
self.__walk(dir, self.__smush)
else:
@@ -146,7 +147,7 @@ def stats(self):
for f in arr:
if f['bytes_saved_percent']:
modified.append(f)
- output.append('%(bytes_saved_percent)s%% saved\t[%(input_size)s / %(output_size)s]\t%(name)s' % f)
+ output.append('%(bytes_saved_percent)s%% saved\t[%(input_size)s > %(output_size)s]\t%(name)s' % f)
output.append('Total time taken: %.2f seconds' % (time.time() - self.__start_time))
return {'output': "\n".join(output), 'modified': modified}
@@ -160,7 +161,7 @@ def __checkExclude(self, file):
def main():
try:
- opts, args = getopt.getopt(sys.argv[1:], 'hrqs', ['help', 'recursive', 'quiet', 'strip-meta', 'exclude=', 'list-only' ,'identify-mime'])
+ opts, args = getopt.getopt(sys.argv[1:], 'hrqs', ['help', 'recursive', 'quiet', 'strip-meta', 'exclude=', 'list-only' ,'identify-mime', 'min-percent=', 'save-optimized='])
except getopt.GetoptError:
usage()
sys.exit(2)
@@ -174,7 +175,9 @@ def main():
strip_jpg_meta = False
exclude = ['.bzr', '.git', '.hg', '.svn']
list_only = False
+ min_percent = 5
identify_mime = False
+ save_optimized = None
for opt, arg in opts:
if opt in ('-h', '--help'):
@@ -192,7 +195,10 @@ def main():
exclude.extend(arg.strip().split(','))
elif opt in ('--list-only'):
list_only = True
- # quiet = True
+ elif opt in ('--min-percent'):
+ min_percent = int(arg)
+ elif opt in ('--save-optimized'):
+ save_optimized = arg
else:
# unsupported option given
usage()
@@ -209,7 +215,10 @@ def main():
format='%(asctime)s %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
- smush = Smush(strip_jpg_meta=strip_jpg_meta, exclude=exclude, list_only=list_only, quiet=quiet, identify_mime=identify_mime)
+ smush = Smush(strip_jpg_meta=strip_jpg_meta, exclude=exclude, list_only=list_only, quiet=quiet, identify_mime=identify_mime, min_percent=min_percent, save_optimized=save_optimized)
+
+ if save_optimized and os.path.isdir(save_optimized):
+ shutil.rmtree(save_optimized, True)
for arg in args:
try:
@@ -237,13 +246,16 @@ def usage():
versions.
Options are any of:
- -h, --help Display this help message and exit
- -r, --recursive Recurse through given directories optimising images
- -q, --quiet Don't display optimisation statistics at the end
- -s, --strip-meta Strip all meta-data from JPEGs
- --exclude=EXCLUDES comma separated value for excluding files
- --identify-mime Fast identify image files via mimetype
- --list-only Perform a trial run with no changes made
+ -h, --help Display this help message and exit
+ -r, --recursive Recurse through given directories optimising images
+ -q, --quiet Don't display optimisation statistics at the end
+ -s, --strip-meta Strip all meta-data from JPEGs
+ --exclude=EXCLUDES Comma separated value for excluding files
+ --identify-mime Fast identify image files via mimetype
+
+ --list-only Perform a trial run with no changes made
+ --min-percent=INT Minimum percent of optimisation to warn about
+ --save-optimized=DIR Directory to save optimised files
"""
if __name__ == '__main__':

0 comments on commit be6a23f

Please sign in to comment.