Last active
December 26, 2017 20:18
-
-
Save fierroformo/74928dfc6320845e5401645af488ab91 to your computer and use it in GitHub Desktop.
Script for reduces dimensions of images
This file contains hidden or 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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import os | |
import sys | |
from PIL import Image | |
VALID_EXTENSIONS = ['.JPG', '.jpg', '.PNG', '.png', '.BMP', '.bmp'] | |
CURSOR_UP_ONE = '\x1b[1A' | |
ERASE_LINE = '\x1b[2K' | |
def main(folder): | |
count = 0 | |
photos = os.listdir(folder) | |
total = len(photos) | |
for photo in photos: | |
path = '{}/{}'.format(folder, photo) | |
# Check for valid extensions | |
ext = os.path.splitext(path)[1] | |
if ext not in VALID_EXTENSIONS: | |
continue | |
img = Image.open(path) | |
width, height = img.size | |
if width >= 7000 or height >= 7000: | |
width = width / 3 | |
height = height / 3 | |
elif width >= 5000 or height >= 5000: | |
width = int(width / 2.5) | |
height = int(height / 2.5) | |
elif width >= 2000 or height >= 2000: | |
width = width / 2 | |
height = height / 2 | |
# Save image with new dimensions | |
new_img = img.resize((width, height), Image.ANTIALIAS) | |
new_img.save(path, quality=95, optimize=True) | |
count += 1 | |
points = CURSOR_UP_ONE + ERASE_LINE + "." * count + "\n" | |
sys.stdout.write("{}".format(points)) | |
sys.stdout.write( | |
"Progress: {} of {} \r".format(count, total) | |
) | |
sys.stdout.flush() | |
print "Convertiste {} imagenes del directorio {}".format( | |
count, folder | |
) | |
print "\n" | |
print "---- Gracias por utilizar Fotitos.py ----" | |
print "---- Powered by fierroformo ----" | |
if __name__ == '__main__': | |
# | |
# Validate arguments | |
# | |
if len(sys.argv) == 1: | |
folder = 'photos' | |
elif len(sys.argv) == 2: | |
folder = sys.argv[1] | |
else: | |
print "Incorrect arguments" | |
exit() | |
main(folder) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment