
image.png (464.01 KB, 下载次数: 0)
下载附件
2025-6-26 15:13 上传

image.png (17.51 KB, 下载次数: 0)
下载附件
2025-6-26 15:14 上传
from PIL import Image
import os
import sys
def resize_image(input_path, output_path, width, height):
"""按照指定尺寸调整图片大小"""
try:
with Image.open(input_path) as img:
# 确保输出目录存在
output_dir = os.path.dirname(output_path)
if output_dir and not os.path.exists(output_dir):
os.makedirs(output_dir)
# 调整图片大小并保存
resized_img = img.resize((width, height), Image.LANCZOS)
resized_img.save(output_path)
return True
except Exception as e:
print(f"处理图片时出错: {e}")
return False
def get_valid_file_path(prompt, default_ext='.jpg', valid_exts=None):
"""获取有效的文件路径,处理扩展名问题"""
if valid_exts is None:
valid_exts = ['.jpg', '.jpeg', '.png', '.gif', '.bmp']
while True:
path = input(prompt).strip()
# 处理空输入
if not path:
print("错误: 路径不能为空")
continue
# 检查文件扩展名
ext = os.path.splitext(path)[1].lower()
if not ext:
# 没有扩展名,添加默认扩展名
path += default_ext
print(f"未指定扩展名,默认使用 {default_ext}")
return path
elif ext in valid_exts:
return path
else:
print(f"错误: 不支持的文件扩展名 '{ext}'")
print(f"支持的扩展名: {', '.join(valid_exts)}")
def main():
"""程序主函数"""
print("=== 图片尺寸调整工具 ===")
# 获取输入图片路径
input_path = get_valid_file_path("请输入要处理的图片路径: ")
if not os.path.exists(input_path):
print(f"错误: 文件 '{input_path}' 不存在")
sys.exit(1)
# 获取输出图片路径
output_path = get_valid_file_path("请输入处理后图片的保存路径: ")
# 获取目标尺寸
while True:
try:
width = int(input("请输入目标宽度(像素): ").strip())
height = int(input("请输入目标高度(像素): ").strip())
if width