简单Python脚本统一平滑批处理图片尺寸 -《狗嗨默示录》-

#coding:utf-8
from PIL import Image
import os

srcPath = "D:\学习资料\pic\\0802"
dstPath = "D:\学习资料\pic\\0802\output"
#图片压缩批处理
def compressImage(srcPath,dstPath):
count = 0
for filename in os.listdir(srcPath):
#如果不存在目的目录则创建一个,保持层级结构
if not os.path.exists(dstPath):
os.makedirs(dstPath)
#拼接完整的文件或文件夹路径
srcFile=os.path.join(srcPath,filename)
dstFile=os.path.join(dstPath,filename)
print("============================================================================")
print(srcFile)
print(dstFile)

#如果是文件就处理
if os.path.isfile(srcFile) and srcFile.endswith(".jpg"):
#打开原图片缩小后保存,可以用if srcFile.endswith(".jpg")或者split,splitext等函数等针对特定文件压缩
sImg=Image.open(srcFile)
w,h=sImg.size
print(w,h)
dImg=sImg.resize((720,480),Image.ANTIALIAS) #设置压缩尺寸和选项,注意尺寸要用括号
dImg.save(dstFile) #也可以用srcFile原路径保存,或者更改后缀保存,save这个函数后面可以加压缩编码选项JPEG之类的
print(dstFile+" [compressed succeeded]")
print("============================================================================\n\n")
count +=1
#如果是文件夹就递归
#if os.path.isdir(srcFile):
#compressImage(srcFile,dstFile)
print("共计完成%d张图片的压缩"%count)

if __name__=='__main__':
compressImage(srcPath, dstPath)
posted @ 2017-08-09 09:58  李·狗嗨  阅读(256)  评论(0编辑  收藏  举报