You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于PIL实现文件夹内所有图片的批量尺寸调整?技术求助

Batch Resize All Images in a Folder with Python/Pillow

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 the endswith check to avoid errors.
  • Safe File Saving: We add a -resized suffix to each output file so your original images stay untouched.
  • Error Handling: The try/except block catches issues like corrupted images or unsupported formats, so the script keeps running instead of crashing mid-batch.

How to Use This

  1. Replace ./your-image-folder with the actual path to your image folder (e.g., ./vacation-photos or C:\\Users\\YourName\\Pictures on Windows).
  2. Adjust RESIZE_DIMENSIONS if you need different width/height values.
  3. Add more extensions to IMAGE_EXTENSIONS (like .webp) if you work with other image formats.
  4. Run the script—all resized images will appear in the same folder with the -resized tag.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:19:33