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

 from PIL import Image

 foo = Image.open('path/to/image.jpg')  # My image is a 200x374 jpeg that is 102kb large
 foo.size  # (200, 374)
 
 # 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.

Answer from Ryan G on Stack Overflow
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-compress-images-using-python-and-pil
How to Compress Images Using Python and PIL?
March 27, 2026 - This means that when you decompress the image, it will be identical to the original image. Examples of lossless compression include PNG and TIFF. ... from PIL import Image import io # Create a sample image in memory for demonstration img = Image.new('RGB', (800, 600), color='red') # Get original size original_size = len(img.tobytes()) print(f"Original dimensions: {img.size}") # Resize to half the dimensions width, height = img.size new_size = (width//2, height//2) resized_img = img.resize(new_size) # Calculate compressed size compressed_size = len(resized_img.tobytes()) print(f"Compressed dimensions: {resized_img.size}") print(f"Size reduction: {((original_size - compressed_size) / original_size) * 100:.1f}%")
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-compress-images-using-python-and-pil
How to compress images using Python and PIL? - GeeksforGeeks
July 15, 2025 - Assemble all the files in a folder and keep the file Compress.py in the same folder. Run the python file with python. ... # run this in any directory # add -v for verbose # get Pillow (fork of PIL) from # pip before running --> # pip install ...
Discussions

How to compress a picture less than a limit file size using python PIL library? - Stack Overflow
I need to send a picture to another place, where it requires picture size must be less than 512kb. I use PIL to deal with my picture which download from internet. so I don't know what will be the n... More on stackoverflow.com
🌐 stackoverflow.com
Trying to compress images with PIL but the file size isn't changing.
The images are probably already optimized and compressed. Why wouldn't they be? You may get a few percent better if you use a program specifically designed to optimize compression, which PIL is not. More on reddit.com
🌐 r/learnpython
8
6
December 15, 2022
I had a genius moment this morning... use python to compress images to webp!
if you dont support webp, you dont deserve my sites ಠ_ಠ More on reddit.com
🌐 r/Frontend
19
0
December 27, 2023
Compress images with Python and PIL | python project for beginners

Does this use middle out compression?

More on reddit.com
🌐 r/Python
2
3
April 29, 2022
Top answer
1 of 10
224

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

 from PIL import Image

 foo = Image.open('path/to/image.jpg')  # My image is a 200x374 jpeg that is 102kb large
 foo.size  # (200, 374)
 
 # 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.

2 of 10
31

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 = Image.open(b.cover_pic.path)
image.save(b.image.path,quality=20,optimize=True)

hope it helps to anyone stumbling upon it.

🌐
DEV Community
dev.to › khatrivinay › compress-images-size-with-python-4ipj
Compress Images size with Python - DEV Community
August 27, 2022 - from turtle import width import ...presed_image.fp.read())/1024,2), "KB") ... We can also download an image from the web and compresses it using the Python pillow library....
🌐
Medium
medium.com › @omcar17295 › how-to-compress-images-using-python-2bfae115dca1
How to compress images using Python | by Omkar Mohan Joshi | Medium
January 1, 2023 - Below is the Python code for compressing the images stored in a folder. import os from PIL import Image # Set the quality of the output image (higher is better quality but larger file size) quality = 85 # Set the directory where the images are ...
🌐
AbstractAPI
abstractapi.com › api guides, tips & tricks › how to compress images with python
Python Compress Image: How to Compress Images with Python (2023)
June 10, 2026 - The easiest way to lower image resolution in Python is to use Pillow. First, use the PIL Image object to open the image file. Next, write the image data to a new file, passing a quality option that lowers the quality of the final image.
🌐
AskPython
askpython.com › home › compress png image in python using pil
Compress PNG image in Python using PIL - AskPython
April 22, 2023 - Call this function with your image file to get a compressed version, allowing for storage optimization and faster transfers while maintaining image quality. In Python, numerous libraries contain pre-defined functions for a variety of purposes. Pillow (PIL) is a popular library in Python for ...
Find elsewhere
🌐
The Python Code
thepythoncode.com › article › compress-images-in-python
How to Compress Images in Python - The Python Code
Learn how to reduce image file size by compressing and resizing the image using Pillow library in Python.
🌐
Understanding Data
understandingdata.com › posts › how-to-easily-resize-compress-your-images-in-python
How To Easily Resize & Compress Your Images In Python
As different social media platforms ... with python can definitely save you time. To learn how to resize a single image. To learn how to resize multiple images within the current working directory. from PIL import Image import PIL import os import glob · As well as compressing an image, ...
Top answer
1 of 2
2

When you're changing the quality using PIL, the dimensions of the image does not change, it just changes the quality of the image using JPEG compression. By default the value is at 80, and thus changing the value to 75 will not reduce the size by much, you can change the value to about 60 without loosing a lot of picture quality. The value reduces logarithmically so if you want the exact math, you can read about JPEG compression. https://math.dartmouth.edu/archive/m56s14/public_html/proj/Marcus_proj.pdf

2 of 2
2

Unfortunately this is a property of JPEG compression and there is no strict inverse function (you can calculate it mathematically if you want large scale efficiency).

However, you can inefficiently brute force the calculation and get it close with the following. If you don't want the same size, just change the quality to a scaling factor and it should work similarly.

import os
from PIL import Image

def compress_under_size(size, file_path):
    '''file_path is a string to the file to be custom compressed
    and the size is the maximum size in bytes it can be which this 
    function searches until it achieves an approximate supremum'''

    quality = 90 #not the best value as this usually increases size

    current_size = os.stat(file_path).st_size

    while current_size > size or quality == 0:
        if quality == 0:
            os.remove(file_path)
            print("Error: File cannot be compressed below this size")
            break

        compress_pic(file_path, quality)
        current_size = os.stat(file_path).st_size
        quality -= 5


def compress_pic(file_path, qual):
    '''File path is a string to the file to be compressed and
    quality is the quality to be compressed down to'''
    picture = Image.open(file_path)
    dim = picture.size

    picture.save(file_path,"JPEG", optimize=True, quality=qual) 

    processed_size = os.stat(file_path).st_size

    return processed_size

for file in os.listdir("pics"):
    try:
        pic = f"./pics/{file}"
        compress_under_size(10000,pic)
    except Exception:
        pass
🌐
Noerguerra
noerguerra.com › a-guide-to-efficient-image-compression-with-python
A guide to efficient image compression with Python – Noé R. Guerra
January 11, 2022 - You can apply lossy and lossless compression to image files with Python using the Pillow Library.
🌐
Python Examples
pythonexamples.org › python-pillow-compress-image
Python Pillow - Compress Image
You can compress an image using Pillow library in Python to a relatively lesser size in memory. To compress an image using Pillow, call Image.save() method on the Image object, and specify True for optimize parameter, and an integer value for quality parameter.
🌐
Thecodersblog
thecodersblog.com › home › programming › compress the image using python
Compress the image using python – The Coders Blog | Home
December 6, 2022 - The quality parameter is supported by the following image formats: JPEG, WebP, and TIFF. from PIL import Image ## ... http POST request image = Image.open(request.files['image']) image.save('image_compressed.jpg', optimize=True, quality=50)
🌐
woteq
woteq.com › home › compressing images to a specific file size in python using pil
Compressing Images to a Specific File Size in Python using PIL - Woteq Zone
February 10, 2026 - Learn how to programmatically compress images to specific file sizes using Python's PIL library. Step-by-step guide with code examples for optimizing website performance.
🌐
YouTube
youtube.com › watch
Compress images in python with pillow module - YouTube
Blog post - https://nagasudhir.blogspot.com/2024/09/compress-photos-in-bulk-with-pillow.htmlIterating through files inside a folder using the glob module in ...
Published   October 5, 2024
🌐
Understanding Data
understandingdata.com › posts › how-to-compress-multiple-images-in-python
How To Compress Multiple Images In Python - Just Understanding Data
There many libraries that allow you to easily optimise images with Python: Pillow – This library builds on top of PIL and can be used for the following image formats: PNG, PPM, JPEG, GIF, BMP and TIFF. img4web – This script optimises .jpg and .png images for the web, after running it you’ll receive lossless compression for the images.
🌐
PyPI
pypi.org › project › optimize-images
optimize-images
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
Plain English
python.plainenglish.io › how-to-compress-image-using-python-4f1deeb24bd9
How to Compress Images using Python | by Rajat upadhyaya | Python in Plain English
January 7, 2025 - How to Compress Images using Python We will see how we can compress our images using Python. For this, I am using the pillow library and also tkinter for selecting an image from the system. Let’s …
🌐
Medium
medium.com › @greeshmapogula11 › image-compression-using-python-fcf353f8c2
Image Compression using Python. Many of us have encountered this issue… | by Greeshma Pogula | Medium
April 3, 2023 - The save function accepts three parameters first one is the name that we need to save our image, the second one is set optimization which in this case needed to be True, and the third is the quality reduction that we can specify. To understand the quality parameter, The image that we provide is having a quality of 100% then here 80 in input makes the quality reduced by 80% then the saved image will be having 20% quality. The higher the quality is given as a parameter the greater the compression rate is. So this is about the compression of images using python. Using PIL we can also make other modifications to our image.