需求分析
在日常生活中经常有需要调整图片大小的需求,一张两张的还好,但是如果需要几十张几百张甚至几千张,然后还是在不同的目录下,这个时候我们就可以考虑使用脚本来执行,于是我就想到了简单方便的python来执行
效果图
废话不多说,先来张运行图

实现
环境要求
- 安装python3,测试时使用的是3.11版本,具体和环境配置可以百度一下,有很多教程
- 该脚本需要cmd窗口执行下列语句安装相关python库
pip install Pillow
具体实现
- 新建一个.py的脚本
- 将下列代码复制进去保存后运行
import os
import sys
from PIL import Image ## 需要 pip install Pillow 安装相关插件
# 输入相关参数
isEquals = True
while isEquals:
start_path = input("请输入图片所在目录(可包含子文件夹):")
out_path = input("请输入图片生成目录(同名会覆盖):")
isEquals = False
if start_path == out_path :
print("\n所在目录和生成目录不能为同一个!\n")
isEquals = True
pass
# 读取路径下所有文件
isPrint = False
for root, dirs, files in os.walk(start_path):
#逐个读取文件
for file in files:
path = root + "\\" + file
# 判断是否是图片文件
if ".png" in path or ".jpg" in path:
img = Image.open(path)
print("\n原始图片分辨率(宽 * 高):" + str(img.size))
isPrint = True
break
if isPrint:
break
width = int(input("\n请输入图片宽度:"))
height = int(input("请输入图片高度:"))
print("\n所在目录: " + start_path)
print("生成目录: " + out_path)
print("目标图片宽高: " + str(width) + " * "+ str(height))
index = 0
# 读取路径下所有文件
for root, dirs, files in os.walk(start_path):
print("\n当前路径:" + root) # 打印路径
# 输入路径
temp_path = out_path + root[len(start_path) : len(root)]
#判断路径是否存在
if not os.path.exists(temp_path):
os.mkdir(temp_path)
print("输出路径:" + temp_path) # 打印路径
#逐个读取修改文件
for file in files:
path = root + "\\" + file
save_path = temp_path + "\\" + file
# 判断是否是图片文件
if ".png" in path or ".jpg" in path:
img = Image.open(path)
im_resized = img.resize((width, height))
im_resized.save(save_path)
print("\n处理完成\n")
os.system("pause")
注意事项
该脚本没有做太多的检测和安全验证,使用时请多注意输入的路径、图片大小的准确性
本文介绍了如何使用Python脚本批量修改大量图片的大小,适用于不同目录下的图片调整。首先分析了需求,然后展示了脚本运行效果。脚本要求Python3环境,并需要安装相关库。代码示例提供了一个简单的实现,但警告使用者在实际操作时要注意输入路径和设置的图片尺寸准确性。

868

被折叠的 条评论
为什么被折叠?



