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
🌐
The Python Code
thepythoncode.com › article › compress-images-in-python
How to Compress Images in Python - The Python Code
The image size is reduced to 379.25KB from 425.65KB, which is about an 11% reduction. Next, let's try to pass -j for converting from PNG to JPEG: $ python compress_image.py sample-satellite-images.png -j
🌐
DEV Community
dev.to › khatrivinay › compress-images-size-with-python-4ipj
Compress Images size with Python - DEV Community
August 27, 2022 - Image compression is a process where we minimize the size of the image without degrading the image quality. To compress the Image in Python we can use the pillow library which is an open source third party library.
Discussions

python - How to reduce the image file size using PIL - Stack Overflow
If you're wanting to keep the same ... save the image. Check out this answer 2012-05-15T19:42:32.163Z+00:00 ... but the quality attribute makes no difference for png formats.even i change the quality the file size remains same. 2012-05-15T19:47:14.417Z+00:00 ... In that case i'm afraid I don't know. PNG's are traditionally larger in size due to their compression ... More on stackoverflow.com
🌐 stackoverflow.com
How to compress a picture less than a limit file size using python PIL library? - Stack Overflow
I use PIL to deal with my picture which download from internet. so I don't know what will be the next picture's size, code like this: Copyfrom PIL import Image picture_location = '/var/picture/1233123.jpg' compressed_picture_location = '/var/picture/1233123_compressed.jpg' im = Image.open(... More on stackoverflow.com
🌐 stackoverflow.com
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
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
🌐
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 located input_dir = '/home/path/to/image_folder' # Set the directory where the compressed images will be saved output_dir = 'compressed_images' # Create the output directory if it does not exist if not os.path.exists(output_dir): os.makedirs(output_dir)
🌐
Understanding Data
understandingdata.com › posts › how-to-easily-resize-compress-your-images-in-python
How To Easily Resize & Compress Your Images In Python
However in our scenario, we would like not only to reduce the size of the images but also to compress them, therefore we will add on the following paramter to this line: img.save('resized-image_'+image, optimize=True, quality=30) for image in multiple_images: img = Image.open(image) img.thumbnail(size=(300,300)) print(img) img.save('resized-image_'+image, optimize=True, quality=30) Now you can easily both resize and compress your images using Python 🥰!
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-compress-images-using-python-and-pil
How to compress images using Python and PIL? - GeeksforGeeks
July 15, 2025 - 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 Pillow # import required libraries import os import sys from PIL import Image # define a function for # compressing an image def compressMe(file, verbose = False): # Get the path of the file filepath = os.path.join(os.getcwd(), file) # open the image picture = Image.open(filepath) # Save the picture with desired quality # To change the quality of image, # set the quality variable at # your desired level, The more # the value of quality var
🌐
Javatpoint
javatpoint.com › how-to-compress-images-in-python
How to Compress Images in Python - Javatpoint
How to Compress Images in Python with tutorial, tkinter, button, overview, canvas, frame, environment set-up, first python program, etc.
🌐
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 - In this article, we'll look at two different methods for compressing images using python: using the PIL library, and using the AbstractAPI Free Image Compression API. ... Before we start, let's take a moment to define the difference between ...
Find elsewhere
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.

🌐
TutorialsPoint
tutorialspoint.com › how-to-compress-images-using-python-and-pil
How to Compress Images Using Python and PIL?
July 20, 2023 - Optimize: When set to True, enables additional compression techniques without quality loss. Format: Choose JPEG for photographs, PNG for images with transparency, and WebP for modern web applications. Image compression using Python and PIL offers flexible options including resizing, quality adjustment, and format optimization.
🌐
Sempioneer
sempioneer.com › python-for-seo › how-to-compress-images-in-python
How To Easily Compress Images With Python!
June 15, 2020 - You will then need to select the specific quality of image from 0 – 100: A quality of 85 doesn’t make much difference for 5 – 6mb files, and shantanujoshi found that 65 for the quality argument is the lowest reasonable number. picture.save("Compressed_"+file_name,optimize=True,quality=30) However, I tried with the quality set at 30 and the two images still seemed similar in terms of image quality. ... We will use Python’s OS package to find and compress every image within the current working directory:
🌐
Rick Wierenga
rickwierenga.com › blog › machine learning › image-compressor-in-Python.html
Compressing images using Python
August 23, 2019 - Then we get our feature matrix \(X\). We’re reshaping the image because each pixel has the same meaning (color), so they don’t have to be presented as a grid. X = image.reshape((w * h, d)) K = 20 # the desired number of colors in the compressed image
🌐
Bytescrum
blog.bytescrum.com › compressing-and-cropping-images-without-losing-quality-in-python
Compressing and Cropping Images Without Losing Quality in Python
September 13, 2024 - import cv2 import imageio from PIL import Image def compress_image_pillow(input_path, output_path, quality=85): with Image.open(input_path) as img: img.save(output_path, "JPEG", quality=quality) def crop_image_pillow(input_path, output_path, crop_area): with Image.open(input_path) as img: cropped_img = img.crop(crop_area) cropped_img.save(output_path) def crop_and_compress_image_pillow(input_path, output_path, crop_area, quality=85): with Image.open(input_path) as img: cropped_img = img.crop(crop_area) cropped_img.save(output_path, "JPEG", quality=quality) def compress_image_opencv(input_path,
🌐
PySeek
pyseek.com › home › how to compress an image using python: a detailed guide
How to Compress an Image using Python: A Detailed Guide
June 10, 2024 - Resize image: The image is resized by half its original size using resize() with Antialiasing for quality. Extract filename and extension: We extract these for constructing the compressed file name. Compose compressed filename: The new filename includes the original name with ‘-compressed’ added. Convert to RGB (if needed): For JPEG saving, the image is converted to RGB mode if necessary.
🌐
Aspose
kb.aspose.com › imaging › python › compress-image-in-python
Compress Image in Python - Aspose Knowledge Base
August 21, 2024 - By following the steps above, you can easily incorporate the feature of JPG compress in Python. First, you may configure the environment by importing the relevant namespaces inside the project. Next, access the input image from the disk and set the compression level along with other properties. Finally, export the output compressed image to the disk or stream according to your requirements.
🌐
Cloudinary
cloudinary.com › home › python image optimization | processing, compression, and resizing
Python Image Optimization | Processing, Compression, and Resizing
November 7, 2025 - With Pillow, which extends the Python Imaging Library (PIL) by adding more features and support for Python 3. Pillow works with many image formats, including PNG, JPEG, PPM, GIF, TIFF, and BMP. With img4web, a Python script that optimizes JPEGs, PNGs, and animated GIFs on the web. The script produces lossless and only slightly compressed images, which nonetheless reduce load time and bandwidth. With smush.py, a Python command-line tool (derived from Yahoo’s smush.it service) that functions as a lossless image optimizer for displaying images.
🌐
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 …
🌐
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 - Stores the directory where the images are located in directory. Defines a max size for each image. ... Open as an Image object. Define a new file name with _compressed appended at the end. Resize to max_size if the image is larger than max_size. Save with the new file name and 85% quality (if JPG) or 256 colors at most (if PNG). Pillow provides a simple way to perform complex operations on your images using Python.
🌐
Understanding Data
understandingdata.com › posts › how-to-compress-multiple-images-in-python
How To Compress Multiple Images In Python - Just Understanding Data
You will then need to select the specific quality of image from 0 – 100: A quality of 85 doesn’t make much difference for 5 – 6mb files, and shantanujoshi found that 65 for the quality argument is the lowest reasonable number. picture.save("Compressed_"+file_name,optimize=True,quality=30) However, I tried with the quality set at 30 and the two images still seemed similar in terms of image quality. We will use Python’s OS package to find and compress every image within the current working directory:
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