Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce the image file size using PIL

I am using PIL to resize the images there by converting larger images to smaller ones. Are there any standard ways to reduce the file size of the image without losing the quality too much, lets say the original size of the image is 100KB, i want to get it down to like 5 or 10 KB especially for png and jpeg formats.

like image 758
Yashwanth Kumar Avatar asked May 15 '12 19:05

Yashwanth Kumar


People also ask

How do I make a picture smaller on PIL?

To resize an image, you call the resize() method on it, passing in a two-integer tuple argument representing the width and height of the resized image. The function doesn't modify the used image; it instead returns another Image with the new dimensions.

How do you compress an image using Python and PIL?

Those who know a bit of python can install python and use pip install pillow in command prompt(terminal for Linux users) to install pillow fork. Assemble all the files in a folder and keep the file Compress.py in the same folder. Run the python file with python.

How do I reduce the size of a JPEG in Python?

getsize(image_name) # print the size before compression/resizing print("[*] Size before compression:", get_size_format(image_size)) if new_size_ratio < 1.0: # if resizing ratio is below 1.0, then multiply width & height with this ratio to reduce image size img = img. resize((int(img. size[0] * new_size_ratio), int(img.


1 Answers

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 = Image.open("path\\to\\image.jpg")  >>> foo.size   (200,374)  # I downsize the image with an ANTIALIAS filter (gives the highest quality)  >>> foo = foo.resize((160,300),Image.ANTIALIAS)  >>> foo.save("path\\to\\save\\image_scaled.jpg",quality=95)  # The saved downsized image size is 24.8kb  >>> foo.save("path\\to\\save\\image_scaled_opt.jpg",optimize=True,quality=95)  # 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 isn't affected much, and the file size is much smaller.

like image 169
Ryan G Avatar answered Oct 09 '22 21:10

Ryan G