Skip to content

Instantly share code, notes, and snippets.

@tarasyarema
Forked from ShantanuJoshi/compressMe.py
Last active September 13, 2019 10:59
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 tarasyarema/d7c77d220a09b3d32b910e1d2ada5c42 to your computer and use it in GitHub Desktop.
Save tarasyarema/d7c77d220a09b3d32b910e1d2ada5c42 to your computer and use it in GitHub Desktop.
Python Image Compress
# Reference
# https://shantanujoshi.github.io/python-image-compression/
import os
import sys
from PIL import Image
def compressMe(file, verbose=False):
filepath = os.path.join(os.getcwd(), file)
oldsize = os.stat(filepath).st_size
try:
picture = Image.open(filepath)
except OSError as e:
print("Could not open file as image: {}".format(e))
return None
except Exception as e:
print("Raised unkown exception: {}".format(e))
return None
dim = picture.size
try:
picture.load()
background = Image.new("RGB", picture.size, (255, 255, 255))
background.paste(picture, mask=picture.split()[3])
picture = background
except:
pass
picture.save("Compressed_"+file, "JPEG", optimize=True, quality=70)
newsize = os.stat(os.path.join(os.getcwd(), "Compressed_"+file)).st_size
percent = (oldsize-newsize)/float(oldsize)*100
if verbose:
print("File compressed from {0} to {1} or {2}%".format(
oldsize, newsize, percent))
return percent
def main():
verbose = False
# checks for verbose flag
if (len(sys.argv) > 1):
if (sys.argv[1].lower() == "-v"):
verbose = True
pwd = os.getcwd()
tot = 0
num = 0
for file in os.listdir(pwd):
percent = compressMe(file, verbose)
if percent is None:
continue
num += 1
tot += percent
if num > 0:
print("Average Compression: %d" % (float(tot)/num))
print("Done")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment