Python Batch Image Resizing Guide
To resize images in bulk, you can utilize Python’s PIL library(short for Python Imaging Library).
Here is a sample code to resize all images in a specified directory to a specific size:
from PIL import Image
import os
# 指定目录和目标大小
directory = 'path/to/images'
target_size = (300, 300)
# 遍历目录中的所有图片
for filename in os.listdir(directory):
if filename.endswith('.jpg') or filename.endswith('.png'):
filepath = os.path.join(directory, filename)
try:
# 打开图片
img = Image.open(filepath)
# 缩放图片
img.thumbnail(target_size)
# 保存图片
img.save(filepath)
print(f"Resized {filename}")
except:
print(f"Failed to resize {filename}")
In the above code, we first specify the directory and target size to be processed. We then use the os.listdir() function to iterate through all the files in the directory, filtering out image files that end with “.jpg” or “.png”.
For each image file, we open the image using the Image.open() function from the PIL library, then scale the image to the desired size using the thumbnail() function. Finally, we save the modified image using the save() function.
If the images to be processed are very large or numerous, one option to consider is using multi-threading or parallel processing to speed up the process.