Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Python pillow library image optimization sample code


Python pillow library image optimization sample code


here is a sample Python code using the Pillow library for bulk image optimization:

python
import os
from PIL import Image

# Set the input and output directories
input_dir = 'path/to/input/directory'
output_dir = 'path/to/output/directory'

# Set the desired image quality (0-100, higher is better quality)
quality = 80

# Loop through all files in the input directory
for filename in os.listdir(input_dir):
    # Check if the file is an image
    if filename.endswith('.jpg') or filename.endswith('.png'):
        # Open the image
        image_path = os.path.join(input_dir, filename)
        image = Image.open(image_path)

        # Optimize the image
        image.save(os.path.join(output_dir, filename), optimize=True, quality=quality)
        print(f'Optimized {filename}')

Here's how the code works:

1. Import the necessary modules: `os` for file system operations and `PIL` (Pillow) for image processing.
2. Set the input and output directories for the images.
3. Set the desired image quality (0-100, higher is better quality).
4. Loop through all files in the input directory.
5. Check if the file is an image (in this case, JPEG or PNG).
6. Open the image using `Image.open()`.
7. Save the optimized image to the output directory using `image.save()` with the `optimize=True` and `quality=quality` parameters.
8. Print a message to indicate that the image has been optimized.

This script will go through all the images in the input directory, optimize them using the specified quality setting, and save the optimized images to the output directory.

You can customize the script further by:

- Adding support for more image formats (e.g., GIF, TIFF)
- Providing command-line arguments for the input/output directories and quality setting
- Implementing batch processing for better performance
- Adding progress indicators or logging for larger image sets

The key benefits of using the Pillow library for bulk image optimization are its simplicity, flexibility, and cross-platform compatibility. Pillow provides a wide range of image processing capabilities, making it a popular choice for Python-based image optimization tasks.

Citations:
[1] https://www.holisticseo.digital/python-seo/image-optimization/
[2] https://flowygo.com/en/blog/pillow-optimize-images-with-python/
[3] https://www.geeksforgeeks.org/python-pillow-tutorial/
[4] https://realpython.com/image-processing-with-the-python-pillow-library/
[5] https://github.com/carzam87/python-bulk-image-optimizer