现在网络上很多工具都能实现按要求压缩图片的需求,但是很多时候我们需要自定义需求,这篇博客就教给大家怎么怎么批量压缩图片大小。
本文目标
把图片按比率批量进行压缩
上代码吧
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#coding:utf-8 #author:py40.com import Image import os #图片压缩批处理 def compressImage(srcPath,dstPath): 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(srcFile) print(dstFile) #如果是文件就处理 if os.path.isfile(srcFile): #打开原图片缩小后保存,可以用if srcFile.endswith(".jpg")或者split,splitext等函数等针对特定文件压缩 sImg=Image.open(srcFile) w,h=sImg.size print w,h dImg=sImg.resize((w/2,h/2),Image.ANTIALIAS) #设置压缩尺寸和选项,注意尺寸要用括号 dImg.save(dstFile) #也可以用srcFile原路径保存,或者更改后缀保存,save这个函数后面可以加压缩编码选项JPEG之类的 print(dstFile+" compressed succeeded") #如果是文件夹就递归 if os.path.isdir(srcFile): compressImage(srcFile,dstFile) if __name__=='__main__': compressImage("./src","./dst") |
运行效果
执行脚本前
执行脚本后
未经允许不得转载:Python在线学习 » python脚本:批量压缩图片大小