这个是将当前目录下所有图片转换为1920X1080尺寸的JPG格式文件,并按序号命名保存的python代码。
from PIL import Image
import os
# 目标尺寸(横向)
target_width = 1920
target_height = 1080
# 支持的图片文件扩展名
image_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.gif')
# 获取当前目录下所有图片文件
image_files = [f for f in os.listdir('.') if f.lower().endswith(image_extensions)]
# 按顺序处理图片
for i, image_file in enumerate(image_files, start=1):
try:
# 打开图片
with Image.open(image_file) as img:
width, height = img.size
# 计算裁剪区域
aspect_ratio = width / height
target_aspect_ratio = target_width / target_height
if aspect_ratio > target_aspect_ratio:
# 图片太宽,裁剪左右两侧
new_width = int(height * target_aspect_ratio)
left = (width - new_width) // 2
right = left + new_width
top = 0
bottom = height
else:
# 图片太高,裁剪上下两侧
new_height = int(width / target_aspect_ratio)
top = (height - new_height) // 2
bottom = top + new_height
left = 0
right = width
# 裁剪图片
cropped_img = img.crop((left, top, right, bottom))
# 调整裁剪后的图片大小到目标尺寸
resized_img = cropped_img.resize((target_width, target_height), Image.LANCZOS)
# 生成新的文件名
new_filename = f"{str(i).zfill(2)}.jpg"
# 保存为JPEG格式
resized_img.save(new_filename, 'JPEG')
print(f"已将 {image_file} 转换并保存为 {new_filename}")
except Exception as e:
print(f"处理 {image_file} 时出错: {e}")