python脚本编程:批量压缩图片大小
2015-12-10 13:20
721 查看
需要安装第三方模块PIL
注意:
尽量用别的目录保存压缩后的图片,不要用源目录保存,比如compressImage(“./src”,”./src”)很容易出错
压缩后
代码
#coding:utf-8 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")
注意:
尽量用别的目录保存压缩后的图片,不要用源目录保存,比如compressImage(“./src”,”./src”)很容易出错
效果
压缩前压缩后
相关文章推荐
- ML--HMM(隐马尔可夫模型及python的实现1)
- Python中的三目运算符
- python2.7.10
- Python多线程2:sched
- 用python抢火车票
- python序列化(数据本地存放持久性存储)和反序列化
- python编码问题
- 【python】常用的日期和时间操作
- Python下pickle加载文件问题
- Python模块学习系列(2)----struct
- Python1
- python:使用socket模块,进行服务器与客户端简单交互
- python中的subprocess子进程
- python configParser 模板
- python基础教程共60课-第21课函数的参数
- Beginning Python Chapter5
- python 编码
- Python模块学习系列(1)----glob
- python内建Exception类型
- Python常用内建模块