这个是将当前目录下所有图片转换为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}")
【编号2559】高效便捷!随机选择指定数量文件工具 V1.0,一键搞定文件随机筛选需求
【编号2541】AI批量图生图工具全能版:自动化批量加水印+多任务并行处理,Windows高效图片制作神器
【编号2542】AI图像识别工具_v1.0.2:高效图像识别 + 人机交互验证、九宫格验证码自动化操作一站式解决方案
【编号2582】图片批量AI编辑工具:让批量图像处理效率提升 10 倍的智能工具
【编号2419】全能 HTML/WORD 转 TXT 转换器:一键搞定多格式文本提取,高效办公必备工具
【编号2439】二维码批量生成工具个性化二维码设计二维码批量导出多格式二维码制作高效二维码生成软件带文字二维码工具自定义样式二维码企业二维码批量生成