zoukankan      html  css  js  c++  java
  • Python 批量修改图片格式和尺寸

    公司的一个项目要求把所有4096x4096的图片全部转化成2048x2048的图片,这种批量转换图片大小的软件网上很多,我的同事原来使用的美图看看的批量转换,但是稍微有点麻烦,每次还需要指定要转换的图片的输入路径和输出路径,而且每次都只能处理一个文件夹,很繁琐,于是我想到了万能的Python,然后写了一个脚本来批量处理图片,同一个根目录下的所有文件夹的子文件等的图片全部会处理掉。大笑

    代码中还加入了很多的异常捕获机制和提示,希望对大家有帮助。

    备注:

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

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

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

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

    [python] view plain copy 在CODE上查看代码片派生到我的代码片
      1. #coding=utf-8  
      2. import sys  
      3. import os, glob  
      4. import platform  
      5. import win32file,win32con  
      6. from PIL import Image  
      7. from send2trash import send2trash  
      8.   
      9. reload(sys)  
      10. sys.setdefaultencoding('utf-8')  
      11.   
      12. #new_width =2048  
      13. #width =int(raw_input("the width U want:"))  
      14. #imgslist = glob.glob(path+'/*.*')  
      15.   
      16. ShuiPing="水平"  
      17. ShiZhuang="矢状"  
      18. GuanZhuang="冠状"  
      19.   
      20. def Py_Log(_string):  
      21.     print "----"+_string.decode('utf-8')+"----"  
      22.   
      23. def is_windows_system():  
      24.     return 'Windows' in platform.system()  
      25.   
      26. def is_hiden_file(file_Path):   
      27.     if is_windows_system():   
      28.         fileAttr = win32file.GetFileAttributes(file_Path)  
      29.         if fileAttr & win32con.FILE_ATTRIBUTE_HIDDEN :   
      30.             return True   
      31.         return False   
      32.     return False  
      33.   
      34. def remove_hidden_file(file_path):  
      35.     send2trash(file_path)  
      36.     print "Delete hidden file path:"+file_path  
      37.   
      38. def astrcmp(str1,str2):  
      39.     return str1.lower()==str2.lower()  
      40.   
      41. def resize_image(img_path):  
      42.     try:  
      43.         mPath, ext = os.path.splitext(img_path)  
      44.         if (astrcmp(ext,".png") or astrcmp(ext,".jpg")):  
      45.             img = Image.open(img_path)  
      46.             (width,height) = 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,quality=100)  
      53.                 Py_Log("图片尺寸修改为:"+str(new_width))  
      54.             else:  
      55.                 Py_Log("图片尺寸正确,未修改")  
      56.         else:  
      57.             Py_Log("非图片格式")  
      58.     except Exception,e:  
      59.         print e  
      60.   
      61. #改变图片类型  
      62. def change_img_type(img_path):  
      63.     try:  
      64.         img = Image.open(img_path)  
      65.         img.save('new_type.png')  
      66.     except Exception,e:  
      67.         print e  
      68.   
      69. #处理远程图片  
      70. def handle_remote_img(img_url):  
      71.     try:  
      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.         (width,height) = img.size  
      78.         out = img.resize((200,height * 200 / width),Image.ANTIALIAS)  
      79.         out.save('remote_small.jpg')  
      80.     except Exception,e:  
      81.         print e  
      82.   
      83. def rename_forder(forder_path):  
      84.     Py_Log("------------rename_forder--------------------------")  
      85.     names = os.path.split(forder_path)  
      86.     try:  
      87.         if(unicode(ShuiPing) in unicode(names[1],'gbk')):  
      88.             os.rename(forder_path,names[0]+"\"+"01")  
      89.             Py_Log(names[1]+"-->"+"01")  
      90.         if(unicode(ShiZhuang) in unicode(names[1],'gbk')):  
      91.             os.rename(forder_path,names[0]+"\"+"02")  
      92.             Py_Log(names[1]+"-->"+"02")  
      93.         if(unicode(GuanZhuang) in unicode(names[1],'gbk')):  
      94.             os.rename(forder_path,names[0]+"\"+"03")  
      95.             Py_Log(names[1]+"-->"+"03")  
      96.     except Exception,e:  
      97.         print e  
      98.   
      99. def BFS_Dir(dirPath, dirCallback = None, fileCallback = None):  
      100.     queue = []  
      101.     ret = []  
      102.     queue.append(dirPath);  
      103.     while len(queue) > 0:  
      104.         tmp = queue.pop(0)  
      105.         if(os.path.isdir(tmp)):  
      106.             ret.append(tmp)  
      107.             for item in os.listdir(tmp):  
      108.                 queue.append(os.path.join(tmp, item))  
      109.             if dirCallback:  
      110.                 dirCallback(tmp)  
      111.         elif(os.path.isfile(tmp)):  
      112.             ret.append(tmp)  
      113.             if fileCallback:  
      114.                 fileCallback(tmp)  
      115.     return ret  
      116.   
      117. def DFS_Dir(dirPath, dirCallback = None, fileCallback = None):  
      118.     stack = []  
      119.     ret = []  
      120.     stack.append(dirPath);  
      121.     while len(stack) > 0:  
      122.         tmp = stack.pop(len(stack) - 1)  
      123.         if(os.path.isdir(tmp)):  
      124.             ret.append(tmp)  
      125.             for item in os.listdir(tmp):  
      126.                 stack.append(os.path.join(tmp, item))  
      127.             if dirCallback:  
      128.                 dirCallback(tmp)  
      129.         elif(os.path.isfile(tmp)):  
      130.             ret.append(tmp)  
      131.             if fileCallback:  
      132.                 fileCallback(tmp)  
      133.     return ret  
      134.   
      135. def printDir(dirPath):  
      136.     print "dir: " + dirPath  
      137.     if(is_hiden_file(dirPath)):  
      138.         remove_hidden_file(dirPath)  
      139.     else:  
      140.         rename_forder(dirPath)  
      141.   
      142. def printFile(dirPath):  
      143.     print "file: " + dirPath  
      144.     resize_image(dirPath)  
      145.     return True  
      146.   
      147.   
      148. if __name__ == '__main__':  
      149.     while True:  
      150.         path = raw_input("Path:")  
      151.         new_width =int(raw_input("the width U want:"))  
      152.         try:  
      153.             b = BFS_Dir(path , printDir, printFile)  
      154.             Py_Log ("           ********** "+"*********图片处理完毕*********"+"           ********** ")  
      155.         except:  
      156.             print "Unexpected error:", sys.exc_info()  
      157.         raw_input('press enter key to rehandle') 
  • 相关阅读:
    连载《一个程序猿的生命周期》-《发展篇》- 6.2016年发展元年,本职工作和个人事业均有突破和起色
    转载 | 北漂纪实:70后最幸福、80后买不起房、90后一手烂牌
    连载《一个程序猿的生命周期》-《发展篇》
    连载《一个程序猿的生命周期》-《发展篇》
    连载《一个程序猿的生命周期》-《发展篇》
    连载《一个程序猿的生命周期》-《发展篇》
    连载《一个程序猿的生命周期》-《发展篇》
    随笔《一个程序猿的生命周期》- 拉风险投资搞创业是一种病吗?
    ubuntu 解决安装dpkg 依赖错误
    Ubuntu 卸载 nginx 并重新安装
  • 原文地址:https://www.cnblogs.com/zhoug2020/p/6701610.html
Copyright © 2011-2022 走看看