python – How to reduce the image file size using PIL

python – How to reduce the image file size using PIL

A built-in parameter for saving JPEGs and PNGs is optimize.

 >>> from PIL import Image
 # My image is a 200x374 jpeg that is 102kb large
 >>> foo =\to\image.jpg)
 >>> foo.size
 # I downsize the image with an ANTIALIAS filter (gives the highest quality)
 >>> foo = foo.resize((160,300),Image.ANTIALIAS)
 # The saved downsized image size is 24.8kb
 # The saved downsized image size is 22.9kb

The optimize flag will do an extra pass on the image to find a way to reduce its size as much as possible. 1.9kb might not seem like much, but over hundreds/thousands of pictures, it can add up.

Now to try and get it down to 5kb to 10 kb, you can change the quality value in the save options.
Using a quality of 85 instead of 95 in this case would yield:
Unoptimized: 15.1kb
Optimized : 14.3kb
Using a quality of 75 (default if argument is left out) would yield:
Unoptimized: 11.8kb
Optimized : 11.2kb

I prefer quality 85 with optimize because the quality isnt affected much, and the file size is much smaller.

lets say you have a model called Book and on it a field called cover_pic,
in that case, you can do the following to compress the image:

from PIL import Image
b = Book.objects.get(title=Into the wild)
image =,quality=20,optimize=True)

hope it helps to anyone stumbling upon it.

python – How to reduce the image file size using PIL

See the thumbnail function of PILs Image Module. You can use it to save smaller versions of files as various filetypes and if youre wanting to preserve as much quality as you can, consider using the ANTIALIAS filter when you do.

Other than that, Im not sure if theres a way to specify a maximum desired size. You could, of course, write a function that might try saving multiple versions of the file at varying qualities until a certain size is met, discarding the rest and giving you the image you wanted.

Leave a Reply

Your email address will not be published.