首页 > 技术文章 > Python批量修改图片格式和尺寸

xuaijun 原文

Python批量修改图片格式和尺寸

备注:

1.导入了PIL库,是处理图片用的,很强大;

2.导入了的win32库,是判断隐藏文件用的,我们的项目需要删除隐藏文件,不需要的可以直接找到删除。

3.导入send2trash库,是把删除的文件放进垃圾箱,而不是永久删除,这个我只是防止删除有用的文件而搞得,有点严谨了是吧,不需要的可以删掉啊。

4.我这个脚本是Python2.7编写的,但是在处理中文编码的时候非常恶心,尽管最后被我解决了,这个解决的方法,我随后会再单独写一篇,但是此刻我是建议大家不要用2.x版本的python了。据说3.x的版本的已经解决了编码的问题。希望大家听我的建议。

[python] 查看纯文本 
 
  1. #编码= utf-8的  
  2. 导入 系统  
  3. 导入 os,glob  
  4. 导入 平台  
  5. 导入 win32file,win32con  
  6.  PIL  导入 图像  
  7.  send2trash  导入 send2trash  
  8.   
  9. 重装(SYS)  
  10. sys.setdefaultencoding('utf-8' )  
  11.   
  12. #new_width = 2048  
  13. #width = int(raw_input(“width U want:”))  
  14. #imgslist = glob.glob(路径+'/ *。*')  
  15.   
  16. ShuiPing = “水平”  
  17. ShiZhuang = “矢状”  
  18. GuanZhuang = “冠状”  
  19.   
  20. def  Py_Log(_string):  
  21.     打印“----” + _string.decode('utf-8' )+ “----”   
  22.   
  23. def  is_windows_system():  
  24.     返回“窗口”  platform.system()    
  25.   
  26. def  is_hiden_file(file_Path):   
  27.     如果 is_windows_system():   
  28.         fileAttr = win32file.GetFileAttributes(file_Path)  
  29.         如果 fileAttr&win32con.FILE_ATTRIBUTE_HIDDEN:   
  30.             返回True    
  31.         返回False    
  32.     返回False   
  33.   
  34. def  remove_hidden_​​file(file_path):  
  35.     send2trash(FILE_PATH)  
  36.     打印“删除隐藏的文件路径:” + file_path   
  37.   
  38. def  astrcmp(str1,str2):  
  39.     返回 str1.lower()== str2.lower()  
  40.   
  41. def  resize_image(img_path):  
  42.     尝试:  
  43.         mPath,ext = os.path.splitext(img_path)  
  44.         如果 (astrcmp(ext,“.  png ” )  astrcmp(ext,“.jpg” )):  
  45.             img = Image.open(img_path)  
  46.             (宽度,高度)= img.size  
  47.               
  48.             if (width!= new_width):  
  49.                 new_height = int(height * new_width / width)  
  50.                 out = img.resize((new_width,new_height),Image.ANTIALIAS)  
  51.                 new_file_name =  '%s%s'  %(mPath,ext)  
  52.                 out.save(new_file_name,质量= 100 )  
  53.                 Py_Log(“图片尺寸修改为:” + str(new_width))  
  54.             其他:  
  55.                 Py_Log(“图片尺寸正确,未修改” )  
  56.         其他:  
  57.             Py_Log(“非图片格式” )  
  58.     除了 例外,e:  
  59.         打印 e  
  60.   
  61. #改变图片类型  
  62. def  change_img_type(img_path):  
  63.     尝试:  
  64.         img = Image.open(img_path)  
  65.         img.save('new_type.png' )  
  66.     除了 例外,e:  
  67.         打印 e  
  68.   
  69. #处理远程图片  
  70. def  handle_remote_img(img_url):  
  71.     尝试:  
  72.         request = urllib2.Request(img_url)  
  73.         img_data = urllib2.urlopen(request).read()  
  74.         img_buffer = StringIO.StringIO(img_data)  
  75.         img = Image.open(img_buffer)  
  76.         img.save('remote.jpg' )  
  77.         (宽度,高度)= img.size  
  78.         out = img.resize((200 ,height *  200  / width),Image.ANTIALIAS)  
  79.         out.save('remote_small.jpg' )  
  80.     除了 例外,e:  
  81.         打印 e  
  82.   
  83. def  rename_forder(forder_path):  
  84.     Py_Log(“------------ rename_forder --------------------------” )  
  85.     names = os.path.split(forder_path)  
  86.     尝试:  
  87.         如果(UNICODE(热水瓶)   的Unicode(名称[ ],'GBK' )):  
  88.             os.rename(forder_path,名称[ ] + “\”+“ 01 ”)  
  89.             Py_Log(名称[ ] + “ - >” “01” )  
  90.         如果(unicode(石庄)  in  unicode(names [ ],'gbk' )):  
  91.             os.rename(forder_path,名称[ ] + “\”+“ 02 ”)  
  92.             Py_Log(名称[ ] + “ - >” “02” )  
  93.         如果(unicode(管庄)  in  unicode(names [ ],'gbk' )):  
  94.             os.rename(forder_path,名称[ ] + “\”+“ 03 ”)  
  95.             Py_Log(名称[ ] + “ - >” “03” )  
  96.     除了 例外,e:  
  97.         打印 e  
  98.   
  99. def  BFS_Dir(dirPath,dirCallback =  None ,fileCallback =  None ):  
  100.     队列= []  
  101.     ret = []  
  102.     queue.append(dirPath);  
  103.      len(队列)>  :  
  104.         tmp = queue.pop()  
  105.         如果(os.path.isdir(tmp)):  
  106.             ret.append(TMP)  
  107.             对于 项目   os.listdir(TMP):  
  108.                 queue.append(os.path.join(tmp,item))  
  109.             如果 dirCallback:  
  110.                 dirCallback(TMP)  
  111.         elif (os.path.isfile(tmp)):  
  112.             ret.append(TMP)  
  113.             如果 fileCallback:  
  114.                 fileCallback(TMP)  
  115.     返回 RET  
  116.   
  117. def  DFS_Dir(dirPath,dirCallback =  None ,fileCallback =  None ):  
  118.     stack = []  
  119.     ret = []  
  120.     stack.append(dirPath);  
  121.      len(stack)>  :  
  122.         tmp = stack.pop(len(stack) -  )  
  123.         如果(os.path.isdir(tmp)):  
  124.             ret.append(TMP)  
  125.             对于 项目   os.listdir(TMP):  
  126.                 stack.append(os.path.join(tmp,item))  
  127.             如果 dirCallback:  
  128.                 dirCallback(TMP)  
  129.         elif (os.path.isfile(tmp)):  
  130.             ret.append(TMP)  
  131.             如果 fileCallback:  
  132.                 fileCallback(TMP)  
  133.     返回 RET  
  134.   
  135. def  printDir(dirPath):  
  136.     打印“dir:”  + dirPath   
  137.     if (is_hiden_file(dirPath)):  
  138.         remove_hidden_​​file(dirPath)  
  139.     其他:  
  140.         rename_forder(dirPath)  
  141.   
  142. def  printFile(dirPath):  
  143.     打印“文件:”  + dirPath   
  144.     resize_image(dirPath)  
  145.     返回True   
  146.   
  147.   
  148. 如果 __name__ == __main__  :  
  149.     :   
  150.         path = raw_input(“Path:” )  
  151.         new_width = int(raw_input(“width U want:” ))  
  152.         尝试:  
  153.             b = BFS_Dir(path,printDir,printFile)  
  154.             Py_Log(“ r n ********** r n” “*********图片处理完毕*********” “ r n ********** r n“ )  
  155.         除了:  
  156.             打印“意外的错误:” ,sys.exc_info()   
  157.         raw_input('按回车键重新处理' )  

 

推荐阅读