Image Resizer Project (code) in Python

← Back to Projects

Image Resizer Script in Python.

About the project: This is a project for an Image Resizer in Python. This will be a self-contained command-line script that allows you to resize an image to specific dimensions.

Before You Run the Code

This project relies on the Pillow library, which is a powerful image manipulation tool. You'll need to install it before running the script. Open your terminal or command prompt and run the following command:


  pip install Pillow
  

The script will prompt you for the path of the image you want to resize, the new width and height you desire, and where to save the new image file.


This project provides a robust and user-friendly command-line tool. It includes error handling for file not found and invalid input, making it more reliable than a simple script.

Project Level: Intermediate

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

Steps: Follow these steps

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE)




# image_resizer.py

import os
import sys
from PIL import Image

def get_numeric_input(prompt, min_value=1):
    """
    Helper function to get a valid positive integer from the user.
    
    Args:
        prompt (str): The message to display to the user.
        min_value (int): The minimum acceptable value (defaults to 1).
        
    Returns:
        int: The validated integer input.
    """
    while True:
        try:
            value = int(input(prompt).strip())
            if value >= min_value:
                return value
            else:
                print(f"Please enter a number greater than or equal to {min_value}.")
        except ValueError:
            print("Invalid input. Please enter a whole number.")

def resize_image(input_path, output_path, new_width, new_height):
    """
    Resizes an image to the specified width and height.
    
    Args:
        input_path (str): The file path of the image to resize.
        output_path (str): The file path to save the resized image.
        new_width (int): The new width in pixels.
        new_height (int): The new height in pixels.
    """
    try:
        # Open the image file
        img = Image.open(input_path)

        # Get the original size for display
        original_width, original_height = img.size
        print(f"Original image size: {original_width}x{original_height} pixels.")

        # Resize the image using the LANCZOS filter for high quality
        # This filter is great for downscaling images
        resized_img = img.resize((new_width, new_height), Image.LANCZOS)
        
        # Save the resized image
        resized_img.save(output_path)
        
        print(f"Successfully resized image saved to: {output_path}")

    except FileNotFoundError:
        print(f"Error: The file '{input_path}' was not found.")
        print("Please check the file path and try again.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

def main():
    """
    Main function to run the Image Resizer tool.
    """
    print("--- Python Image Resizer ---")

    while True:
        input_image_path = input("Enter the path to the image you want to resize: ").strip()
        if not input_image_path:
            print("Input path cannot be empty.")
            continue
            
        # Check if the user wants to quit
        if input_image_path.lower() == 'q':
            print("Exiting Image Resizer. Goodbye!")
            sys.exit(0)

        # Get the new dimensions
        new_width = get_numeric_input("Enter the new width in pixels: ")
        new_height = get_numeric_input("Enter the new height in pixels: ")
        
        # Create a default output filename if one isn't provided
        base, ext = os.path.splitext(input_image_path)
        default_output_path = f"{base}_resized{ext}"
        
        output_path = input(f"Enter the output path (e.g., resized_image.jpg), or press Enter for default '{default_output_path}': ").strip()
        if not output_path:
            output_path = default_output_path
        
        resize_image(input_image_path, output_path, new_width, new_height)
        
        # Ask if the user wants to perform another operation
        play_again = input("\nDo you want to resize another image? (yes/no): ").strip().lower()
        if play_again != 'yes':
            print("Exiting Image Resizer. Goodbye!")
            break

# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
    main()





← Back to Projects