How to Compress Images for Website Screenshots Using Python?

Estimated read time 2 min read

To compress images for website screenshots using Python, you can utilize the Pillow library, which provides image processing capabilities. Here’s an example of how you can compress images for website screenshots:

from PIL import Image
import io

def compress_image(image_path, output_path, max_width, max_height, quality):
    # Open the image
    with Image.open(image_path) as image:
        # Resize the image while maintaining aspect ratio
        image.thumbnail((max_width, max_height), Image.ANTIALIAS)
        
        # Create a BytesIO object to hold the compressed image
        image_buffer = io.BytesIO()
        
        # Save the image to the buffer with the specified quality
        image.save(image_buffer, format="JPEG", quality=quality)
        
        # Write the buffer contents to the output file
        with open(output_path, "wb") as output_file:
            output_file.write(image_buffer.getvalue())

# Example usage
input_path = "screenshot.png"
output_path = "compressed_screenshot.jpg"
max_width = 1280
max_height = 720
compression_quality = 80  # Adjust the quality value as desired (0-100)

compress_image(input_path, output_path, max_width, max_height, compression_quality)

In this example, the compress_image() function takes five parameters: the input image path, the output image path, the maximum width, the maximum height, and the compression quality. The function first opens the image using Image.open() from Pillow. It then resizes the image while maintaining its aspect ratio using image.thumbnail().

Next, a BytesIO object is created to hold the compressed image. The image.save() method is used to save the image to the buffer with the specified compression quality. The image data is retrieved from the buffer using image_buffer.getvalue().

Finally, the compressed image data is written to the output file using open() and write().

You can adjust the max_width and max_height parameters to set the maximum dimensions for the compressed image. Images larger than these dimensions will be resized to fit within these constraints while maintaining their aspect ratio.

Similarly, you can adjust the compression_quality parameter to control the compression level of the resulting image.

Ensure that you have the Pillow library installed. You can install it using pip:

pip install pillow

By using Pillow and the provided code, you can compress images for website screenshots, resize them to fit desired dimensions, and control the compression quality to optimize the image file size for web usage.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply