如何基于PIL实现文件夹内所有图片的批量尺寸调整?技术求助
No problem! Let's take your single-image resize code and expand it to handle every image in a folder in one go. Here's a straightforward solution with explanations:
First, Quick Setup Check
You already have Pillow and resizeimage installed, so we just need Python's built-in os module (no extra installs required) to scan and manage files in your folder.
The Batch Resize Script
This code will process every image in your target folder, resize them using the same resize_cover method you're already using, and save resized versions without overwriting your original files:
from PIL import Image from resizeimage import resizeimage import os # Configure these values to match your needs TARGET_FOLDER = "./your-image-folder" # Replace with your actual folder path RESIZE_DIMENSIONS = [200, 100] # Keep your desired width/height here IMAGE_EXTENSIONS = ('.jpeg', '.jpg', '.png', '.gif') # Add more formats if needed # Loop through every file in the target folder for filename in os.listdir(TARGET_FOLDER): # Skip any non-image files if not filename.lower().endswith(IMAGE_EXTENSIONS): continue # Build full paths for input and output files input_file_path = os.path.join(TARGET_FOLDER, filename) # Create a unique output filename (adds "-resized" to avoid overwrites) file_name, file_ext = os.path.splitext(filename) output_filename = f"{file_name}-resized{file_ext}" output_file_path = os.path.join(TARGET_FOLDER, output_filename) # Process the image (mirrors your single-image workflow) try: with open(input_file_path, 'r+b') as f: with Image.open(f) as image: resized_image = resizeimage.resize_cover(image, RESIZE_DIMENSIONS) resized_image.save(output_file_path, image.format) print(f"✅ Resized successfully: {filename}") except Exception as e: print(f"❌ Failed to resize {filename}: {str(e)}")
Key Details to Note
- Folder Traversal:
os.listdir(TARGET_FOLDER)grabs every file in your specified folder—we filter out non-images with theendswithcheck to avoid errors. - Safe File Saving: We add a
-resizedsuffix to each output file so your original images stay untouched. - Error Handling: The
try/exceptblock catches issues like corrupted images or unsupported formats, so the script keeps running instead of crashing mid-batch.
How to Use This
- Replace
./your-image-folderwith the actual path to your image folder (e.g.,./vacation-photosorC:\\Users\\YourName\\Pictureson Windows). - Adjust
RESIZE_DIMENSIONSif you need different width/height values. - Add more extensions to
IMAGE_EXTENSIONS(like.webp) if you work with other image formats. - Run the script—all resized images will appear in the same folder with the
-resizedtag.
Bonus: Save to a Separate Folder
If you don't want resized images cluttering your original folder, create a new folder (e.g., ./resized-images) and update the output_file_path line to:
output_file_path = os.path.join(TARGET_FOLDER, "resized-images", output_filename)
Just make sure the resized-images folder exists before running the script!
内容的提问来源于stack exchange,提问作者xxxx

