compress jpg image in python

To compress a JPEG image in Python, you can use the PIL library. Here's an example code snippet that compresses a JPEG image file:

main.py
from PIL import Image

def compress(image_path, output_path, quality):
    """
    Compress the given JPEG image file with the specified quality
    and save it to the given output path.
    """
    with Image.open(image_path) as image:
        image.save(output_path, 'JPEG', quality=quality)
294 chars
10 lines

To use this function, you simply need to call it with the input and output file paths, as well as the desired quality level (between 1 and 95, where 95 is the highest quality):

main.py
input_path = 'example.jpg'
output_path = 'compressed.jpg'
quality = 50

compress(input_path, output_path, quality)
115 chars
6 lines

This will compress the example.jpg file with a quality level of 50 and save the output to compressed.jpg. You can adjust the quality parameter to achieve the desired compression level.

gistlibby LogSnag