Introduction
The python program resizes an image using the pillow library.it prompts the user for the image name,desired output filename,file format(JPG or PNG),and new dimensions.The program checks if the image exists,resizes it to the specified dimensions,and saves it with the new name.it also includes basic error handling to ensure valid inputs and proper file operations.
program
from PIL import Image import os def resize_image(image, resized, size): if not os.path.exists(image): print(f"Error: The input image '{image}' does not exist.") return try: with Image.open(image) as img: print(f"Original size: {img.size}") resized_img = img.resize(size) resized_img.save(resized) print(f"Resized image saved to '{resized}' with size {size}") except Exception as e: print(f"Error occurred: {e}") try: file = input("Enter the image name (without extension): ") rename = input("Enter the new name for the resized image (without extension): ") choose = int(input("Choose extension : jpg(1) or png(2) [1/2]: ")) if choose == 1: image_name = file + '.jpg' resize_name = rename + '.jpg' elif choose == 2: image_name = file + '.png' resize_name = rename + '.png' else: raise ValueError("Invalid choice. Please enter '1' for JPG or '2' for PNG.") width = int(input("Enter width: ")) height = int(input("Enter height: ")) new_size = (width, height) resize_image(image_name, resize_name, new_size) except ValueError as e: print(f"Error:{e}. Please enter valid numbers for the width, height, and file extension choice.")
Explanation
importing required modules
from PIL import Image import os
PIL(pillow):Image is imported from the python imaging library(PIL)module.This is used to open,manipulate,and save image files.
os:This module is imported to handle file system interactions,specifically to check whether the input image file exists.
Function definition resize_image
def resize_image(image, resized, size):
resize_image():This function is responsible for resizing an image and saving the resized image to a new file.
check if the input image exists
if not os.path.exists(image): print(f"Error: The input image '{image}' does not exist.") return
os.path.exists():This checks whether the file path for the image exists.
Error handling:if the image doesn’t exist an error message is printed and the function returns early without doing anything else.
open and resize the image
with Image.open(image) as img: print(f"Original size: {img.size}")
image.open():This opens the image file specified by the image parameter.
img.size:This property prints the original dimensions(width,height)of the image to provide feedback to the user.
resized_img = img.resize(size)
img.resize(size):Resizes the image to the dimensions specified by the size tuple.This will create new image object with the new size.
save the resized image
resized_img.save(resized) print(f"Resized image saved to '{resized}' with size {size}")
resized_img_save():saves the resized image to the file path given by the resized parameter.
The function prints a message confirming that the resized image has been successfully saved.
Handle errors in the image processing
except Exception as e: print(f"Error occurred: {e}")
Any errors that occur during the image opening,resizing,or saving process are caught here.The error message is printed to help the user debug what went wrong.
Main Code Block:user input and logic
try: file = input("Enter the image name (without extension): ") rename = input("Enter the new name for the resized image (without extension): ") choose = int(input("Choose extension : jpg(1) or png(2) [1/2]: "))
.user input
The user provides the name of the image they want to resize,without the file extension.
The user provides the new name for the resized image,again without the extension.
The user selects the format they want the resized image saved in,either JPEG or PNG.This is done by choosing 1(for JPG) or 2(for PNG).The input is converted to an integer.
Determining file extensions
if choose == 1: image_name = file + '.jpg' resize_name = rename + '.jpg' elif choose == 2: image_name = file + '.png' resize_name = rename + '.png' else: raise ValueError("Invalid choice. Please enter '1' for JPG or '2' for PNG.")
Based on the user’s choice of format (choose),the script appends either .jpg or .png to both the input file name and resized file names.
if the user inputs anything other than 1 or 2,a value error is raised ,which is caught letter.
Resizing dimension input
width = int(input("Enter width: ")) height = int(input("Enter height: ")) new_size = (width, height)
The user provides the dimensions for the resized image,and these are converted to integers.
new_size:This is a tuple that stores the width and height to be passed to the resize_image() function.
call the resize_image Function
resize_image(image_name, resize_name, new_size)
The resize_image() function is called with the constructed file names and the new size as arguments,triggering the resizing and saving of the image.
Error handling for user input
except ValueError as e: print(f"Error:{e}. Please enter valid numbers for the width, height, and file extension choice.")
This block catches any valueError exceptions .An error message is displayed to guide the user to provide valid inputs.
output
conclusion
The image resizer script provides a simple yet effective tool for resizing images interactively, allowing users to specify custom dimensions and output formats (JPEG or PNG). With built-in error handling, the script ensures that invalid inputs are caught and reported, making it user-friendly and reliable.
By utilizing the powerful Pillow (PIL
) library, the script handles image resizing efficiently, while the os
module ensures the input file exists before processing. The overall design is flexible, enabling the user to choose the file name, output format, and desired image size.
This script can be particularly useful in scenarios where images need to be resized for web use, social media, or other applications requiring specific dimensions, offering a straightforward solution to a common problem in image processing.