Created
August 10, 2014 12:37
-
-
Save 1999/53b678c668dea1c8d49d to your computer and use it in GitHub Desktop.
Python3 script to resize photos
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 python3 | |
# | |
# Usage: | |
# resizer.py DIRECTORY_WITH_PHOTOS MAX_WIDTH_HEIGHT | |
# | |
# Example: | |
# resizer.py ~/Dropbox/Camera\ Uploads 2048 | |
import os | |
import sys | |
import subprocess | |
import fnmatch | |
BOLD = '\033[1m' | |
RED = '\033[91m' | |
ENDC = '\033[0m' | |
GREEN = '\033[92m' | |
SUPPORTED_EXTENSIONS = ('.jpg', '.jpeg', '.JPG', '.JPEG') | |
def sysrun(cmd): | |
try: | |
output = subprocess.check_output(cmd.split()) | |
except subprocess.CalledProcessError as ex: | |
print('%s%s[error]%s %s' % (BOLD, RED, ENDC, ex)) | |
sys.exit(ex.returncode) | |
def log(str): | |
print('%s[info]%s %s' % (GREEN, ENDC, str)) | |
if len(sys.argv) != 3: | |
print('Wrong variables number', end='. ') | |
print('Usage: resizer.py DIRECTORY_WITH_PHOTOS HIGHEST_DIMENSION') | |
sys.exit(1); | |
current_dir = os.path.dirname(os.path.realpath(__file__)) | |
photos_dir = sys.argv[1] if sys.argv[1].startswith('/') else current_dir + '/' + sys.argv[1] | |
photos_dir = os.path.realpath(photos_dir) | |
# check for directory existance | |
if not os.path.isdir(photos_dir): | |
print('Specified directory does not exist') | |
sys.exit(1); | |
# check for good dimension | |
dimension = int(sys.argv[2]) | |
if dimension < 1024: | |
print('Wrong width/height used. At least 1024 should be used') | |
sys.exit(1); | |
log('Current script directory: %s' % current_dir) | |
log('Photos directory: %s' % photos_dir) | |
print() | |
originals = [] | |
for root, dirnames, filenames in os.walk(photos_dir, followlinks=True): | |
for filename in filenames: | |
if filename.endswith(SUPPORTED_EXTENSIONS): | |
photo_path = os.path.join(root, filename) | |
split_photo_path = os.path.splitext(filename) | |
photo_copy_path = os.path.join(root, '%s_copy%s' % split_photo_path) | |
log('Original: %s' % photo_path) | |
log('Copy: %s' % photo_copy_path) | |
originals.append(photo_path) | |
log('Start resizing...') | |
sysrun('convert %s -resize %sx%s %s' % (photo_path, dimension, dimension, photo_copy_path)) | |
log('Done!') | |
print() | |
sysrun('open %s' % photos_dir) | |
choice = input('Would you like to delete original photos? (y/N) ') | |
if choice.lower() == 'y': | |
for file_path in originals: | |
log('Delete %s...' % file_path) | |
os.remove(file_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment