Skip to content

Instantly share code, notes, and snippets.

@mitnk
Last active December 10, 2015 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitnk/4359177 to your computer and use it in GitHub Desktop.
Save mitnk/4359177 to your computer and use it in GitHub Desktop.
Small Images with PIL
from PIL import Image
import os
import subprocess
import sys
def smaller_images():
if len(sys.argv) != 3:
print "Usage: python image_smaller.py <Path> 0.X"
return
path = sys.argv[1]
if not path.startswith("/"):
path = os.path.join(os.getcwd(), path)
try:
rate = float(sys.argv[2])
except ValueError:
print "Usage: python image_smaller.py <Path> 0.X"
return
if not os.path.exists(path):
print "Error: Invalid path: %s" % path
return
target_dir = os.path.join(os.getcwd(), "image_smaller_%.2f" % rate)
if os.path.exists(target_dir):
print "Error: Target directory exist (%s)" % target_dir
return
os.mkdir(target_dir)
count = 1
EXTS = ("png", "jpg", "jpeg", "bmp")
file_list = [x for x in os.listdir(path) if x.split('.')[-1].lower() in EXTS]
total = len(file_list)
try:
cols = int(subprocess.check_output(['tput', 'cols']).strip()) - 8
except AttributeError:
cols = 72
width_rate = cols * 1.0 / total
for f in file_list:
print '\r',
print '#' * int(width_rate * count),
fmt_str = '{:%d.1%%}' % (cols - int(width_rate * count) + 6)
percent_rate_str = fmt_str.format(count * 1.0 / total)
print percent_rate_str,
sys.stdout.flush()
img = Image.open(os.path.join(path, f))
new_img = img.resize((int(img.size[0] * rate), int(img.size[1] * rate)),
Image.ANTIALIAS)
new_img.save(os.path.join(target_dir, f), quality=100)
count += 1
print "\nOK. Processed %d Images!" % count
print "Saved at: %s" % target_dir
if __name__ == "__main__":
smaller_images()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment