# How to Use Python for Batch Image Resizing and Compression

Managing a large collection of high-resolution images can be challenging, especially when storage space is limited, or you're preparing images for [web](https://bytescrum.com/) use. Resizing and compressing images in bulk can save space and make your files easier to share or upload. In this tutorial, we’ll build a [Python](https://blog.bytescrum.com/compressing-and-cropping-images-without-losing-quality-in-python) script to resize and compress images in bulk using the `PIL` (Python Imaging Library) module, now known as `Pillow`.

### **Why Resize and Compress Images?**

* **Reduce File Size**: Smaller images use less disk space and are faster to upload and download.
    
* **Improve Website Performance**: Resized and compressed images load faster on web pages, improving user experience.
    
* **Optimize for Different Uses**: Create image sizes suitable for various platforms like social media, web, or print.
    

### **Getting Started**

To create a script that resizes and compresses images, you need to install the `Pillow` library, a powerful tool for image manipulation in Python.

#### **Step 1: Install Pillow**

Install the Pillow library using pip:

```bash
pip install Pillow
```

#### **Step 2: Write the Python Script**

Here’s a Python script that resizes and compresses all images in a specified directory:

```python
from PIL import Image
import os

def resize_and_compress_images(input_dir, output_dir, max_width, max_height, quality):
    """
    Resize and compress images in the input directory and save them to the output directory.
    
    Parameters:
    - input_dir: Directory containing images to process.
    - output_dir: Directory to save processed images.
    - max_width: Maximum width for resizing.
    - max_height: Maximum height for resizing.
    - quality: Quality of the output image (1-100).
    """
    
    # Ensure the output directory exists
    os.makedirs(output_dir, exist_ok=True)

    # Iterate through all files in the input directory
    for filename in os.listdir(input_dir):
        # Construct the full file path
        file_path = os.path.join(input_dir, filename)

        # Open the image file
        with Image.open(file_path) as img:
            # Resize the image
            img.thumbnail((max_width, max_height))

            # Save the compressed image to the output directory
            output_path = os.path.join(output_dir, filename)
            img.save(output_path, optimize=True, quality=quality)

            print(f"Processed {filename} -> {output_path}")

if __name__ == "__main__":
    input_directory = "images/input"   # Directory with original images
    output_directory = "images/output" # Directory for processed images
    max_width = 800                    # Max width for resizing
    max_height = 600                   # Max height for resizing
    quality = 85                       # Image quality (1-100)

    resize_and_compress_images(input_directory, output_directory, max_width, max_height, quality)
```

### **How the Script Works**

1. **Importing Libraries**: The script uses the `Image` class from Pillow to handle image processing.
    
2. **Setting Up Directories**: The script takes an input directory containing the original images and an output directory where the resized and compressed images will be saved.
    
3. **Resizing Images**: The `thumbnail()` method is used to resize images while maintaining the aspect ratio, with the maximum width and height set by the user.
    
4. **Compressing Images**: The `save()` method saves the resized image with the specified quality, optimizing the file size.
    
5. **Processing Each Image**: The script iterates over all files in the input directory, processing each image file and saving the output to the specified directory.
    

### **Running the Script**

1. **Set the Input and Output Directories**: Update the `input_directory` and `output_directory` variables to point to your desired folders.
    
2. **Adjust the Resize and Compression Settings**: Modify the `max_width`, `max_height`, and `quality` variables to match your needs.
    
3. **Execute the Script**: Run the script in your Python environment to process all images in the specified directory.
    

### **Tips for Using the Script**

* **Batch Processing**: This script is ideal for batch processing large numbers of images, saving time and effort.
    
* **Different Image Formats**: Pillow supports various image formats such as JPEG, PNG, GIF, and more, making it versatile for different use cases.
    
* **Custom Resizing**: You can customize the resizing logic to crop images or apply different scaling techniques based on your requirements.
    

<details data-node-type="hn-details-summary"><summary>Conclusion</summary><div data-type="detailsContent">With this Python script, you can easily resize and compress images in bulk, making them more suitable for web use, sharing, or storage. This not only helps in optimizing storage but also ensures faster loading times for websites and applications. Happy coding!</div></details>
