python批量修改图片大小的方法
本文实例为大家分享了python批量修改图片大小的具体代码,供大家参考,具体内容如下
引用的模块
fromPILimportImage
Image的使用
defresize_image(img_path): try: mPath,ext=os.path.splitext(img_path) ifastrcmp(ext,".png")orastrcmp(ext,".jpg"): img=Image.open(img_path) (width,height)=img.size ifwidth!=new_width: new_height=int(height*new_width/width) out=img.resize((new_width,new_height),Image.ANTIALIAS) new_file_name='%s%s'%(mPath,ext) out.save(new_file_name,quality=100) Py_Log("图片尺寸修改为:"+str(new_width)) else: Py_Log("图片尺寸正确,未修改") else: Py_Log("非图片格式") exceptException,e: printe defprintFile(dirPath): print"file:"+dirPath resize_image(dirPath) returnTrue
引用
if__name__=='__main__': path="E:\pp\icon_setting.png" new_width=50 try: b=printFile(path) Py_Log("\r\n**********\r\n"+"*********图片处理完毕*********"+"\r\n**********\r\n") except: print"Unexpectederror:",sys.exc_info()
上述是修改单一的图片,若要批量修改文件夹下的所有图片,则要使用循环,在上面基础添加例如:
defBFS_Dir(dirPath,dirCallback=None,fileCallback=None): queue=[] ret=[] queue.append(dirPath); whilelen(queue)>0: tmp=queue.pop(0) ifos.path.isdir(tmp): ret.append(tmp) foriteminos.listdir(tmp): queue.append(os.path.join(tmp,item)) ifdirCallback: dirCallback(tmp) elifos.path.isfile(tmp): ret.append(tmp) iffileCallback: fileCallback(tmp) returnret
第一个参数为图片的目录路径,第二个参数是(目录路劲的回掉方法),第三个参数是图片处理回掉方法
源代码参考:Python_Tool
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。