准备工作
查看当前已安装的python模块:cmd -> pip list
安装模板 PIL:cmd -> pip install Pillow
所需配置
- 生成的新图存放路径(图片名称与原图相同)
- 缩放值
- 要处理的png所在的根目录(会处理该目录下的所有png,包括子孙级目录下的)
具体代码
ModifyPngSize.py
# 修改目标图片的尺寸
import os
from PIL import Image, ImageFilter
def pathToFileName(path, needSuffix):
'''从路径中获取文件名'''
fileName = path.split('\\')[-1]
if not needSuffix:
fileName = fileName.split('.')[0]
return fileName
def getPathList(path, suffix):
'''获取path下所有后缀为suffix的文件的路径'''
pathList = []
for mainDir, subDir, fileNameList in os.walk(path):
for fileName in fileNameList:
currentPath = os.path.join(mainDir, fileName)
if currentPath.endswith(suffix):
pathList.append(currentPath)
return pathList
def getAllPngPath(path):
return getPathList(path, '.png')
if __name__ == "__main__":
# 生成的新图存放位置(名称与原图相同)
newImgDir = r'新图存放路径'
# 缩放值
scale = 0.5
# png所在的根目录
path = r'要修改的原图所在的根目录'
pngPaths = getAllPngPath(path)
cnt = len(pngPaths)
for i in range(cnt):
curPercentage = str(int(i / cnt * 100)) + '%'
path = pngPaths[i]
with Image.open(path) as image:
newSize = (int(image.size[0] * scale), int(image.size[1] * scale))
newImgPath = os.path.join(newImgDir, pathToFileName(path, True))
newImg = image.resize(newSize)
newImg.save(newImgPath)
print('保存', newImgPath, '进度:', curPercentage)
网友评论