Created
June 12, 2017 15:16
-
-
Save marianoeramirez/4da64c807448591cd0a9c1fc4c9c3930 to your computer and use it in GitHub Desktop.
Python image optimize command
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os, sys | |
from PIL import Image | |
import argparse | |
import time | |
import math | |
def convert_size(size_bytes): | |
if size_bytes == 0: | |
return "0B" | |
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") | |
i = int(math.floor(math.log(size_bytes, 1024))) | |
p = math.pow(1024, i) | |
s = round(size_bytes / p, 2) | |
return "%s %s" % (s, size_name[i]) | |
parser = argparse.ArgumentParser(description='Process and resize images.') | |
#parser.add_argument('integers', metavar='N', type=int, nargs='+', | |
# help='an integer for the accumulator') | |
parser.add_argument("--all", help="increase output verbosity", | |
action="store_true") | |
parser.add_argument('--path', help= 'paste path to biog.txt file') | |
parser.add_argument("--override", help="Override the same file", | |
action="store_true") | |
args = parser.parse_args() | |
start_time = time.time() | |
size = 1280, 1280 | |
files_array = [] | |
total_size = {"total":0, "new" :0} | |
if args.all: | |
for root, dirs, files in os.walk("./"): | |
for file in files: | |
if file.lower().endswith(('.png', '.jpg', '.jpeg')): | |
total_size["total"] += os.path.getsize(os.path.join(root, file)) | |
files_array.append(os.path.join(root, file)) | |
if args.path: | |
for root, dirs, files in os.walk(args.path): | |
for file in files: | |
if file.lower().endswith(('.png', '.jpg', '.jpeg')): | |
total_size["total"] += os.path.getsize(os.path.join(root, file)) | |
files_array.append(os.path.join(root, file)) | |
print("Number of files: %d" % len(files_array)) | |
print("Total size: %s" % convert_size(total_size["total"])) | |
for infile in files_array: | |
name, extension = os.path.splitext(infile) | |
if args.override: | |
outfile = name+ extension | |
else: | |
outfile = name+ "-thumb"+extension | |
try: | |
im = Image.open(infile) | |
im.thumbnail(size, Image.ANTIALIAS) | |
im.save(outfile) | |
total_size["new"] += os.path.getsize(outfile) | |
except IOError: | |
print "cannot create thumbnail for '%s'" % infile | |
print("Total new size: %s" % convert_size(total_size["new"])) | |
print("--- %s seconds ---" % (time.time() - start_time)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment