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.
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()
from PIL import Image
Image
is a core object provided by the Pillow library used for opening, manipulating, and saving many different image file formats.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}")
resize_image(input_path, output_path, width, height)
with Image.open(input_path) as img:
input_path
.resized_img = img.resize((width, height), Image.ANTIALIAS)
Image.ANTIALIAS
is used to apply a high-quality downsampling filter.resized_img.save(output_path)
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)
input_path = input("Enter the path to the image file: ").strip()
output_path = input("Enter the path to save the resized image: ").strip()
int()
to convert the inputs to integers.ValueError
and print an error message, then exit the function.resize_image(input_path, output_path, width, height)
resize_image()
function with the provided inputs.