How to Create an Image Converter in Python

How to Create an Image Converter in Python

Easily Convert Images with the Pillow Library in Python

In today's digital world, image conversion is a common task. Whether you need to change the format of an image for compatibility reasons or optimize its size for faster loading, having a reliable image converter is essential. In this blog, we'll walk through how to create a simple yet powerful image converter in Python using the popular Pillow library.

Prerequisites

Before we dive into the code, ensure you have Python installed on your machine. You'll also need to install the Pillow library. You can install it via pip:

pip install Pillow

Step 1: Importing Required Libraries

First, we'll import the necessary modules from the Pillow library.

from PIL import Image
import os

Step 2: Loading an Image

Let's start by loading an image from your local directory. Ensure you have an image file in the same directory as your script or provide the correct path.

def load_image(image_path):
    try:
        image = Image.open(image_path)
        print(f"Image {image_path} loaded successfully.")
        return image
    except IOError:
        print("Error loading image. Please check the file path.")
        return None

Step 3: Converting the Image Format

Next, we'll create a function to convert the image format. The function will take the image object and the desired output format as arguments.

def convert_image_format(image, output_format, output_path):
    try:
        if output_format.lower() not in ["jpeg", "png", "bmp", "gif", "tiff"]:
            print("Unsupported format. Please choose from 'jpeg', 'png', 'bmp', 'gif', or 'tiff'.")
            return

        output_file = os.path.splitext(output_path)[0] + "." + output_format.lower()
        image.save(output_file, output_format.upper())
        print(f"Image successfully converted to {output_format} and saved as {output_file}.")
    except Exception as e:
        print(f"Error converting image: {e}")

Step 4: Resizing the Image

Image resizing can be essential for various purposes, such as reducing the file size or fitting an image into a specific dimension.

    def resize_image(image, width, height):
    resized_image = image.resize((width, height))
    print(f"Image resized to {width}x{height}.")
    return resized_image

Step 5: Putting It All Together

Now, let's combine everything into a single script where you can load an image, convert its format, and resize it if necessary.

from PIL import Image
import os


def load_image(image_path):
    try:
        image = Image.open(image_path)
        print(f"Image {image_path} loaded successfully.")
        return image
    except IOError:
        print("Error loading image. Please check the file path.")
        return None


def convert_image_format(image, output_format, output_path):
    try:
        if output_format.lower() not in ["jpeg", "png", "bmp", "gif", "tiff"]:
            print(
                "Unsupported format. Please choose from 'jpeg', 'png', 'bmp', 'gif', or 'tiff'.")
            return

        output_file = os.path.splitext(
            output_path)[0] + "." + output_format.lower()
        image.save(output_file, output_format.upper())
        print(
            f"Image successfully converted to {output_format} and saved as {output_file}.")
    except Exception as e:
        print(f"Error converting image: {e}")


def resize_image(image, width, height):
    resized_image = image.resize((width, height))
    print(f"Image resized to {width}x{height}.")
    return resized_image


def main():
    input_path = "input_image.jpg"  # Replace with your input image path
    output_format = "png"  # Desired output format
    output_path = "converted_image.png"  # Output path

    # Load image
    image = load_image(input_path)

    if image is not None:
        # Resize image (optional)
        # Resize to 800x600, adjust as needed
        resized_image = resize_image(image, 800, 600)

        # Convert image format
        convert_image_format(resized_image, output_format, output_path)


if __name__ == "__main__":
    main()

Conclusion
In this blog, we covered the basics of creating an image converter in Python using the Pillow library. We learned how to load an image, convert its format, and resize it. This simple yet powerful script can be extended further to include more functionalities such as image rotation, cropping, and applying filters.

Feel free to customize the code to suit your needs and explore the extensive features that Pillow offers. Happy coding!