经常在某些网站或应用上上传图片说分辨率太小什么的,直接用这个脚本就行
[color=]本地运行,无需网络,上万张图片无损放大几分钟就搞定
这个脚本一键搞定一个目录下所有图片三倍无损放大(递归处理)并覆盖原图
[Python] 纯文本查看 复制代码import os
from PIL import Image
import shutil
def resize_and_replace(image_path):
"""放大图片并覆盖原文件(通过临时文件确保原子性操作)"""
try:
# 打开图片并计算新尺寸
with Image.open(image_path) as img:
width, height = img.size
new_size = (width * 3, height * 3)
# 使用高质量插值算法放大图像
resized_img = img.resize(new_size, Image.Resampling.LANCZOS)
# 根据原格式保存参数优化
file_ext = os.path.splitext(image_path)[1].lower()
temp_path = image_path + ".tmp"
save_args = {'format': img.format, 'quality': 95} if file_ext in ('.jpg', '.jpeg') \
else {'format': img.format, 'optimize': True} if file_ext == '.png' \
else {'format': img.format}
# 保存到临时文件后覆盖原文件
resized_img.save(temp_path, **save_args)
os.replace(temp_path, image_path)
print(f"已处理: {image_path}")
except Exception as e:
print(f"处理失败: {image_path} - 错误: {str(e)}")
if os.path.exists(temp_path):
os.remove(temp_path)
def process_directory(root_dir):
"""递归处理目录下的所有图片"""
for foldername, _, filenames in os.walk(root_dir):
for filename in filenames:
file_path = os.path.join(foldername, filename)
# 检查文件大小和扩展名
if os.path.getsize(file_path) >= 50 * 1024:
continue
if not file_path.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff')):
continue
resize_and_replace(file_path)
'''
图片三倍无损放大
'''
if __name__ == "__main__":
target_dir = input("请输入目标文件夹路径: ").strip()
if os.path.isdir(target_dir):
process_directory(target_dir)
else:
print("路径无效!")