Image Resizer in Python

Resizing images is a common task when working with digital images, whether it’s for web development, graphic design, or simply organizing photos. Python provides several libraries that make it easy to manipulate images, including resizing them. In this example, we’ll use the popular Pillow library (a fork of the Python Imaging Library, or PIL) to create a script that resizes images to a specified width and height. The script will be interactive, asking the user for input on the image file path and the desired dimensions.

Code Example

from PIL import Image

def resize_image(input_path, output_path, width, height):
    try:
        with Image.open(input_path) as img:
            resized_img = img.resize((width, height), Image.ANTIALIAS)
            resized_img.save(output_path)
            print(f"Image saved to {output_path}")
    except Exception as e:
        print(f"An error occurred: {e}")

def main():
    print("Welcome to the Image Resizer!")
    input_path = input("Enter the path to the image file: ").strip()
    output_path = input("Enter the path to save the resized image: ").strip()
    
    try:
        width = int(input("Enter the desired width: "))
        height = int(input("Enter the desired height: "))
    except ValueError:
        print("Invalid input. Please enter numeric values for width and height.")
        return
    
    resize_image(input_path, output_path, width, height)

if __name__ == "__main__":
    main()

Detailed Code Explanation

Importing Required Module

from PIL import Image
  • PIL (Pillow): This module provides extensive file format support, an efficient internal representation, and fairly powerful image processing capabilities. Image is a core object provided by the Pillow library used for opening, manipulating, and saving many different image file formats.

Image Resizing Function

def resize_image(input_path, output_path, width, height):
    try:
        with Image.open(input_path) as img:
            resized_img = img.resize((width, height), Image.ANTIALIAS)
            resized_img.save(output_path)
            print(f"Image saved to {output_path}")
    except Exception as e:
        print(f"An error occurred: {e}")
  1. Function Definition: resize_image(input_path, output_path, width, height)
    • input_path: Path to the original image file.
    • output_path: Path where the resized image will be saved.
    • width: Desired width of the resized image.
    • height: Desired height of the resized image.
  2. Open Image: with Image.open(input_path) as img:
    • Open the image file specified by input_path.
  3. Resize Image: resized_img = img.resize((width, height), Image.ANTIALIAS)
    • Resize the image to the specified width and height. Image.ANTIALIAS is used to apply a high-quality downsampling filter.
  4. Save Resized Image: resized_img.save(output_path)
    • Save the resized image to the specified output path.
  5. Exception Handling:
    • Catch and print any exceptions that occur during the process (e.g., file not found, invalid file format).

Main Function

def main():
    print("Welcome to the Image Resizer!")
    input_path = input("Enter the path to the image file: ").strip()
    output_path = input("Enter the path to save the resized image: ").strip()
    
    try:
        width = int(input("Enter the desired width: "))
        height = int(input("Enter the desired height: "))
    except ValueError:
        print("Invalid input. Please enter numeric values for width and height.")
        return
    
    resize_image(input_path, output_path, width, height)
  1. Greeting: Print a welcome message.
  2. User Input for Paths:
    • input_path = input("Enter the path to the image file: ").strip()
      • Prompt the user to enter the path to the image file.
    • output_path = input("Enter the path to save the resized image: ").strip()
      • Prompt the user to enter the path where the resized image will be saved.
  3. User Input for Dimensions:
    • Prompt the user to enter the desired width and height of the resized image.
    • Use int() to convert the inputs to integers.
    • If the inputs are not valid integers, catch the ValueError and print an error message, then exit the function.
  4. Call Resize Function:
    • resize_image(input_path, output_path, width, height)
    • Call the resize_image() function with the provided inputs.