Skip to content

Instantly share code, notes, and snippets.

@ShantanuJoshi
Last active April 29, 2022 18:15
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save ShantanuJoshi/23ac55479ab9a613230bd9467d080f33 to your computer and use it in GitHub Desktop.
Save ShantanuJoshi/23ac55479ab9a613230bd9467d080f33 to your computer and use it in GitHub Desktop.
Python Image Compress
#run this in any directory add -v for verbose
#get Pillow (fork of PIL) from pip before running --> pip install Pillow
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
picture = Image.open(filepath)
dim = picture.size
#set quality= to the preferred quality.
#I found that 85 has no difference in my 6-10mb files and that 65 is the lowest reasonable number
picture.save("Compressed_"+file,"JPEG",optimize=True,quality=85)
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
#finds present working dir
pwd = os.getcwd()
tot = 0
num = 0
for file in os.listdir(pwd):
if os.path.splitext(file)[1].lower() in ('.jpg', '.jpeg'):
num += 1
tot += compressMe(file, verbose)
print "Average Compression: %d" % (float(tot)/num)
print "Done"
if __name__ == "__main__":
main()
@mcschwartzman
Copy link

Just change print statements to print() and works out of box! Thanks

@Kiritow
Copy link

Kiritow commented Jun 27, 2019

Does not work for me. The compressMe function turns a 397K picture into a 2.3M one...

@ShantanuJoshi
Copy link
Author

Does not work for me. The compressMe function turns a 397K picture into a 2.3M one...

I'd try and play with the picture.save("Compressed_"+file,"JPEG",optimize=True,quality=85) settings I used this for very very large files (10mb) avg so doubt that quality setting would still apply for an already fairly compressed jpg.

@jrtderonde
Copy link

Just change print statements to print() and works out of box! Thanks

I can indeed confirm that this works.

@bofaalsarah
Copy link

Does not work for me. The compressMe function turns a 397K picture into a 2.3M one...

I am experiencing similar behavior

@Feddroid
Copy link

Does not work for a 7mb PNG

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment