Search This Blog

Image Resizing and Conversion with Pillow

 

🖼️ Image Resizing and Conversion with Pillow

When working with images in Python, the Pillow library is the go-to tool for tasks like resizing, converting, and editing. In this post, we’ll dive into how to resize and convert images using Pillow, making it easier to process image files for web optimization, batch editing, or even custom applications.

In this guide, we’ll cover:

✅ How to resize images using Pillow
✅ How to convert images to different formats
✅ Practical examples of both resizing and converting images


🧰 What You’ll Need

  • Python 3.x

  • Pillow library installed (which you can do via pip install Pillow)

  • Some images to work with


📦 Installing Pillow

First, if you haven't already, install Pillow using pip:

pip install Pillow

🖼️ Resizing Images with Pillow

Resizing images is a common task, especially when you need to optimize images for web use or scale them to fit a specific size in your application.

1. Resizing an Image

Here’s a simple example of how to resize an image using Pillow:

from PIL import Image

# Open an image file
with Image.open("example.jpg") as img:
    # Resize the image (keeping the aspect ratio)
    img_resized = img.resize((800, 600))
    
    # Save the resized image
    img_resized.save("resized_example.jpg")

print("Image resized successfully!")

Explanation:

  1. Image.open(): Opens the image from the file.

  2. img.resize(): Resizes the image to the specified dimensions. In this case, it’s resized to 800x600 pixels.

  3. img_resized.save(): Saves the resized image to a new file.

2. Resizing While Maintaining the Aspect Ratio

If you want to resize an image without distorting it (i.e., maintaining the aspect ratio), you can calculate the new dimensions based on the image's original size:

from PIL import Image

# Open the image
with Image.open("example.jpg") as img:
    # Get the original dimensions
    width, height = img.size
    
    # Calculate the new dimensions while maintaining the aspect ratio
    new_width = 800
    new_height = int((new_width / width) * height)
    
    # Resize the image
    img_resized = img.resize((new_width, new_height))
    
    # Save the resized image
    img_resized.save("resized_example_aspect_ratio.jpg")

print("Image resized with aspect ratio!")

Explanation:

  • The new height is calculated by scaling the original height in proportion to the new width, ensuring that the aspect ratio is maintained.


🔄 Converting Images to Different Formats

Pillow also makes it easy to convert images from one format to another, such as from JPG to PNG, or from PNG to GIF.

1. Converting an Image to Another Format

Here’s how to convert an image from JPG to PNG:

from PIL import Image

# Open the image file
with Image.open("example.jpg") as img:
    # Convert the image to PNG format
    img.save("example_converted.png", format="PNG")

print("Image converted to PNG successfully!")

Explanation:

  • img.save(): Saves the image in a different format by specifying the format argument.

You can convert between formats such as JPG, PNG, GIF, TIFF, and others, depending on the image type.


📸 Converting Between Image Modes

Images in Pillow can have different modes, such as RGB, grayscale, or even transparent. You can convert an image to a different mode before saving it.

1. Convert an Image to Grayscale

Here’s how to convert an image to grayscale (black and white):

from PIL import Image

# Open the image file
with Image.open("example.jpg") as img:
    # Convert the image to grayscale
    img_gray = img.convert("L")
    
    # Save the grayscale image
    img_gray.save("grayscale_example.jpg")

print("Image converted to grayscale!")

Explanation:

  • img.convert("L"): Converts the image to grayscale (mode "L" stands for luminance).

2. Convert an Image to RGBA (with Transparency)

If you have an image that doesn’t have transparency (like a JPG), you can convert it to RGBA format, which supports transparency.

from PIL import Image

# Open the image file
with Image.open("example.jpg") as img:
    # Convert the image to RGBA (with transparency)
    img_rgba = img.convert("RGBA")
    
    # Save the image with transparency
    img_rgba.save("example_with_transparency.png")

print("Image converted to RGBA format!")

🔧 Practical Example: Resizing and Converting Multiple Images in a Folder

If you need to resize and convert multiple images in a directory, you can use a loop to process all images at once:

from PIL import Image
import os

# Define the folder containing images
folder_path = "images_folder"

# Loop through all files in the folder
for filename in os.listdir(folder_path):
    if filename.endswith(".jpg"):  # Process only JPG files
        with Image.open(os.path.join(folder_path, filename)) as img:
            # Resize the image
            img_resized = img.resize((800, 600))
            
            # Convert to PNG format
            new_filename = filename.replace(".jpg", ".png")
            img_resized.save(os.path.join(folder_path, new_filename), format="PNG")

print("Batch processing complete!")

Explanation:

  • os.listdir(): Lists all files in the folder.

  • os.path.join(): Constructs the full file path for each image.

  • The images are resized and converted to PNG format.


🧠 Final Thoughts

Pillow provides a powerful and easy-to-use interface for working with images in Python. By resizing and converting images, you can optimize them for web use, create thumbnails, or process batches of images efficiently.

💡 Use Cases:

  • Web Optimization: Resize large images to smaller sizes for faster loading times.

  • Image Conversion: Convert between formats for compatibility or to reduce file size.

  • Batch Processing: Resize and convert multiple images in a folder automatically.


Popular Posts