Compress JPEG image in Python using PIL
In this tutorial, we are going to discuss on how to compress the JPEG image in Python.
Compressing JPEG image in Python:
We know that compression is important to decrease the memory size for storing the image
Here is the code in Python for compressing the JPEG image
import os import sys from PIL import Image def compressimg(f,ver=False): fpath= os.path.join(os.getcwd(),f) oldsize = os.stat(fpath).st_size pic= Image.open(fpath) dim= pict.size pic.save("Compressed_"+file,"JPEG",optimize=True,quality=85) newsize= os.stat(os.path.join(os.getcwd(),"Compressed_"+f)).st_size perc= (oldsize-newsize)/float(oldsize)*100 if (ver): print("File compressed from {0} to {1} or {2}%".format(oldsize,newsize,percent)) return perc def main(): ver=False #checks for verbose flag if (len(sys.argv)>1): if (sys.argv[1].lower()=="-v"): ver=True PWD=os.getcwd()# present working directory t=0 n=1 for f in os.listdir(PWD): if os.path.splitext(f)[1].lower() in ('.jpg','.jpeg'): n+=1 t+=compressimg(f,ver) print("Average Compression:%d" %(float(t)/n)) print("Done") if __name__ == "__main__": main()
Output: File compressed from 900 to 450 or 50 Average Compression:1 Done
From the above example, we understood that the size of the image is compressed to nearly half of its original size. And in this code, we should install the modules for getting the attributes of the image, And for fetching the image as above code.
Also read: Compress an image to minimize memory size in Python
In line 9 you wrote :
dim= pict.size
did you perhaps mean ‘pic’ which was defined a line prior?