图片修改尺寸
这个脚本具有以下功能:
1、处理指定文件夹中所有的 JPG/JPEG 图片
2、将图片调整为 480×640 像素的尺寸,保持原图比例并在空白处填充白色
3、设置分辨率为 300dpi,确保为 24 位真彩色
4、自动调整 JPEG 压缩质量,使文件大小不超过 40KB
5、将处理后的图片保存到与源文件夹同级的 “23 计 3 改 20250918” 文件夹中
import os
import shutil
from PIL import Image
from io import BytesIO
import tracebackdef resize_images(source_dir):"""调整指定文件夹中所有JPG图片的尺寸和参数,包含详细错误处理"""# 目标文件夹名称target_dir_name = "23计3改20250918"target_dir = os.path.join(os.path.dirname(source_dir), target_dir_name)# 创建目标文件夹if os.path.exists(target_dir):shutil.rmtree(target_dir)os.makedirs(target_dir, exist_ok=True)# 目标参数target_width = 480target_height = 640processed_count = 0skipped_count = 0for filename in os.listdir(source_dir):if filename.lower().endswith(('.jpg', '.jpeg')):try:print(f"开始处理: {filename}")img_path = os.path.join(source_dir, filename)# 步骤1: 尝试打开图片try:with Image.open(img_path) as img:# 转换为RGB模式if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):background = Image.new(img.mode[:-1], img.size, (255, 255, 255))background.paste(img, img.split()[-1])img_rgb = background.convert("RGB")elif img.mode != 'RGB':img_rgb = img.convert("RGB")else:img_rgb = img.copy()except Exception as e:raise Exception(f"打开图片失败: {str(e)}")# 步骤2: 调整尺寸try:img_ratio = img_rgb.width / img_rgb.heighttarget_ratio = target_width / target_heightif img_ratio > target_ratio:new_width = target_widthnew_height = int(new_width / img_ratio)else:new_height = target_heightnew_width = int(new_height * img_ratio)resized_img = img_rgb.resize((new_width, new_height), Image.Resampling.LANCZOS)# 创建目标尺寸图像final_img = Image.new('RGB', (target_width, target_height), (255, 255, 255))paste_x = (target_width - new_width) // 2paste_y = (target_height - new_height) // 2final_img.paste(resized_img, (paste_x, paste_y))except Exception as e:raise Exception(f"调整尺寸失败: {str(e)}")# 步骤3: 控制文件大小并保存try:quality = 95target_path = os.path.join(target_dir, filename)buffer = BytesIO()success = Falsewhile quality > 10:buffer.seek(0)buffer.truncate()final_img.save(buffer, 'JPEG', quality=quality, dpi=(300, 300))buffer_size = buffer.tell() # 使用tell()获取大小,更可靠if buffer_size <= 40 * 1024:# 保存到文件with open(target_path, 'wb') as f:buffer.seek(0)f.write(buffer.read())success = Truebreakquality -= 5if not success:# 即使质量很低也要保存buffer.seek(0)buffer.truncate()final_img.save(buffer, 'JPEG', quality=10, dpi=(300, 300))with open(target_path, 'wb') as f:buffer.seek(0)f.write(buffer.read())success = Trueif success:processed_count += 1print(f"成功处理: {filename}")except Exception as e:raise Exception(f"保存图片失败: {str(e)}")except Exception as e:skipped_count += 1print(f"处理 {filename} 时出错: {str(e)}")# 打印详细的错误堆栈跟踪print("错误详情:")traceback.print_exc()else:skipped_count += 1print(f"跳过非JPG文件: {filename}")print(f"\n处理完成!")print(f"成功处理: {processed_count} 个文件")print(f"跳过: {skipped_count} 个文件")print(f"处理后的文件保存在: {target_dir}")if __name__ == "__main__":source_directory = r"C:\Users\XuZhenZhong\Desktop\23计3学测照片\23计3班学测照片20250917"if not os.path.isdir(source_directory):print(f"错误: {source_directory} 不是有效的文件夹路径")else:resize_images(source_directory)