1+ # resize_images.py
2+
3+ import os
4+ import argparse
5+ from PIL import Image
6+
7+ def resize_images (input_folder , output_folder , size ):
8+ """
9+ Resizes all JPG, PNG, and WebP images in a folder to a specified size.
10+
11+ Args:
12+ input_folder (str): The path to the folder containing images.
13+ output_folder (str): The path to the folder to save resized images.
14+ size (tuple): A tuple of (width, height) for the target resolution.
15+ """
16+ # Create the output directory if it doesn't exist
17+ if not os .path .exists (output_folder ):
18+ os .makedirs (output_folder )
19+ print (f"Created directory: { output_folder } " )
20+
21+ # List all files in the input directory
22+ files = os .listdir (input_folder )
23+
24+ for filename in files :
25+ # Check for valid image extensions (case-insensitive) - NOW INCLUDES .webp
26+ if filename .lower ().endswith (('.png' , '.jpg' , '.jpeg' , '.webp' )):
27+ try :
28+ # Construct full file paths
29+ input_path = os .path .join (input_folder , filename )
30+ output_path = os .path .join (output_folder , filename )
31+
32+ # Open, resize, and save the image
33+ with Image .open (input_path ) as img :
34+ # Convert to RGB to avoid issues when saving formats like JPG
35+ # from formats that might have transparency (like PNG or WebP).
36+ rgb_img = img .convert ('RGB' )
37+ resized_img = rgb_img .resize (size )
38+ resized_img .save (output_path )
39+ print (f"Successfully resized { filename } " )
40+
41+ except Exception as e :
42+ print (f"Error processing { filename } : { e } " )
43+
44+ print ("\n Batch resize complete! ✨" )
45+
46+ if __name__ == "__main__" :
47+ # Set up the argument parser
48+ parser = argparse .ArgumentParser (description = "Batch resize images in a folder." )
49+
50+ # Required positional arguments
51+ parser .add_argument ("input_folder" , type = str , help = "Path to the input folder containing images." )
52+ parser .add_argument ("output_folder" , type = str , help = "Path to the folder to save resized images." )
53+
54+ # Required optional argument for size
55+ parser .add_argument ("--size" , type = int , nargs = 2 , required = True , metavar = ('WIDTH' , 'HEIGHT' ),
56+ help = "Target size for resizing (e.g., --size 800 600)." )
57+
58+ args = parser .parse_args ()
59+
60+ # Convert the size list to a tuple
61+ target_size = tuple (args .size )
62+
63+ # Run the main function
64+ resize_images (args .input_folder , args .output_folder , target_size )
0 commit comments