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

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

备注:

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

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

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

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

    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. reload(sys)
    9. sys.setdefaultencoding('utf-8')
    10. #new_width =2048
    11. #width =int(raw_input("the width U want:"))
    12. #imgslist = glob.glob(path+'/*.*')
    13. ShuiPing="水平"
    14. ShiZhuang="矢状"
    15. GuanZhuang="冠状"
    16. def Py_Log(_string):
    17. print "----"+_string.decode('utf-8')+"----"
    18. def is_windows_system():
    19. return 'Windows' in platform.system()
    20. def is_hiden_file(file_Path):
    21. if is_windows_system():
    22. fileAttr = win32file.GetFileAttributes(file_Path)
    23. if fileAttr & win32con.FILE_ATTRIBUTE_HIDDEN :
    24. return True
    25. return False
    26. return False
    27. def remove_hidden_file(file_path):
    28. send2trash(file_path)
    29. print "Delete hidden file path:"+file_path
    30. def astrcmp(str1,str2):
    31. return str1.lower()==str2.lower()
    32. def resize_image(img_path):
    33. try:
    34. mPath, ext = os.path.splitext(img_path)
    35. if (astrcmp(ext,".png") or astrcmp(ext,".jpg")):
    36. img = Image.open(img_path)
    37. (width,height) = img.size
    38. if(width != new_width):
    39. new_height = int(height * new_width / width)
    40. out = img.resize((new_width,new_height),Image.ANTIALIAS)
    41. new_file_name = '%s%s' %(mPath,ext)
    42. out.save(new_file_name,quality=100)
    43. Py_Log("图片尺寸修改为:"+str(new_width))
    44. else:
    45. Py_Log("图片尺寸正确,未修改")
    46. else:
    47. Py_Log("非图片格式")
    48. except Exception,e:
    49. print e
    50. #改变图片类型
    51. def change_img_type(img_path):
    52. try:
    53. img = Image.open(img_path)
    54. img.save('new_type.png')
    55. except Exception,e:
    56. print e
    57. #处理远程图片
    58. def handle_remote_img(img_url):
    59. try:
    60. request = urllib2.Request(img_url)
    61. img_data = urllib2.urlopen(request).read()
    62. img_buffer = StringIO.StringIO(img_data)
    63. img = Image.open(img_buffer)
    64. img.save('remote.jpg')
    65. (width,height) = img.size
    66. out = img.resize((200,height * 200 / width),Image.ANTIALIAS)
    67. out.save('remote_small.jpg')
    68. except Exception,e:
    69. print e
    70. def rename_forder(forder_path):
    71. Py_Log("------------rename_forder--------------------------")
    72. names = os.path.split(forder_path)
    73. try:
    74. if(unicode(ShuiPing) in unicode(names[1],'gbk')):
    75. os.rename(forder_path,names[0]+"\\"+"01")
    76. Py_Log(names[1]+"-->"+"01")
    77. if(unicode(ShiZhuang) in unicode(names[1],'gbk')):
    78. os.rename(forder_path,names[0]+"\\"+"02")
    79. Py_Log(names[1]+"-->"+"02")
    80. if(unicode(GuanZhuang) in unicode(names[1],'gbk')):
    81. os.rename(forder_path,names[0]+"\\"+"03")
    82. Py_Log(names[1]+"-->"+"03")
    83. except Exception,e:
    84. print e
    85. def BFS_Dir(dirPath, dirCallback = None, fileCallback = None):
    86. queue = []
    87. ret = []
    88. queue.append(dirPath);
    89. while len(queue) > 0:
    90. tmp = queue.pop(0)
    91. if(os.path.isdir(tmp)):
    92. ret.append(tmp)
    93. for item in os.listdir(tmp):
    94. queue.append(os.path.join(tmp, item))
    95. if dirCallback:
    96. dirCallback(tmp)
    97. elif(os.path.isfile(tmp)):
    98. ret.append(tmp)
    99. if fileCallback:
    100. fileCallback(tmp)
    101. return ret
    102. def DFS_Dir(dirPath, dirCallback = None, fileCallback = None):
    103. stack = []
    104. ret = []
    105. stack.append(dirPath);
    106. while len(stack) > 0:
    107. tmp = stack.pop(len(stack) - 1)
    108. if(os.path.isdir(tmp)):
    109. ret.append(tmp)
    110. for item in os.listdir(tmp):
    111. stack.append(os.path.join(tmp, item))
    112. if dirCallback:
    113. dirCallback(tmp)
    114. elif(os.path.isfile(tmp)):
    115. ret.append(tmp)
    116. if fileCallback:
    117. fileCallback(tmp)
    118. return ret
    119. def printDir(dirPath):
    120. print "dir: " + dirPath
    121. if(is_hiden_file(dirPath)):
    122. remove_hidden_file(dirPath)
    123. else:
    124. rename_forder(dirPath)
    125. def printFile(dirPath):
    126. print "file: " + dirPath
    127. resize_image(dirPath)
    128. return True
    129. if __name__ == '__main__':
    130. while True:
    131. path = raw_input("Path:")
    132. new_width =int(raw_input("the width U want:"))
    133. try:
    134. b = BFS_Dir(path , printDir, printFile)
    135. Py_Log ("\r\n          **********\r\n"+"*********图片处理完毕*********"+"\r\n          **********\r\n")
    136. except:
    137. print "Unexpected error:", sys.exc_info()
    138. raw_input('press enter key to rehandle')

Python 批量修改图片格式和尺寸的更多相关文章

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

    Python批量修改图片格式和尺寸 备注: 1.导入了PIL库,是处理图片用的,很强大; 2.导入了的win32库,是判断隐藏文件用的,我们的项目需要删除隐藏文件,不需要的可以直接找到删除. 3.导入 ...

  2. python批量修改图片名称

    import os class BatchRename(): def rename(self): # windows环境 """ os.rename() 方法用于命名文件 ...

  3. python 批量修改图片大小

    一个文件夹下面有好多图片格式是jpg大小是1920*1080,把它们处理成1280*720并按原先图片的名保存在另一路径下这里首先要找到给定路径下所有的图片文件,然后在修改图片文件的大小,这里用到PI ...

  4. python 批量更换图片格式脚本

    问题:将某文件下的所有jpg的图片更换为png的图片 简单的实现: # -*- coding:utf-8 -*- from os.path import splitext import glob fr ...

  5. python:批量修改文件名批量修改图片尺寸

    批量修改文件名  参考博客:https://www.cnblogs.com/zf-blog/p/7880126.html 功能:批量修改文件名 1 2 3 4 5 6 7 8 9 10 11 12 1 ...

  6. 使用Adobe Photoshop CC 2015批量修改图片尺寸

    最近在工作中遇到一个问题,当时客户给的图片尺寸与我要求的图片不符,由于图片非常的多,如果一张一张的修改,十分的麻烦,后来经过一位同事的指点,发现Adobe Photoshop CC 2015可以实现批 ...

  7. python 将png图片格式转换生成gif动画

    先看知乎上面的一个连接 用Python写过哪些[脑洞大开]的小工具? https://www.zhihu.com/question/33646570/answer/157806339 这个哥们通过爬气 ...

  8. 【faster-rcnn】训练自己的数据——修改图片格式、类别

    修改图片格式 matlab代码 其实内部一些代码是用了rbg的fast-rcnn代码的. \datasets\VOCdevkit2007\VOCcode\VOCinit.m里面,查找'jpg',改成' ...

  9. 利用python批量修改word文件名的方法示例

    利用python批量修改word文件名的方法示例 最近不小心把硬盘给格式化了,由于当时的文件没有备份,所以一下所有的文件都没有了,于是只能采取补救措施,用文件恢复软件恢复了一部分的数据出来,但是恢复完 ...

随机推荐

  1. eclipse 设置文本模板中 insert variable... 函数 详解

    设置文本模板简要图: 设置文本模板详细过程:http://www.cnblogs.com/lsy131479/p/8478711.html 此处引出设置文本模板中 insert variable... ...

  2. Python实现QQ自动点赞

    用Python做一个QQ自动点赞神器,上代码: 1 def QQZan(qq): 2 browser = webdriver.Chrome() 3 browser.maximize_window() ...

  3. BZOJ 4213 贪吃蛇 上下界费用流 网络流

    https://darkbzoj.cf/problem/4213 https://www.cnblogs.com/DaD3zZ-Beyonder/p/5733326.html 题目描述 dbzoj又崩 ...

  4. [BZOJ 4809] 相逢是问候

    Link: 传送门 Solution: 以前没见过的套路题…… 1.使用EXT欧拉定理降幂的套路: $a^{x}=a^{xmod\phi(P)+\phi(P)} mod P$,且$x\ge P$ 这样 ...

  5. 洛谷.3803.[模板]多项式乘法(NTT)

    题目链接:洛谷.LOJ. 为什么和那些差那么多啊.. 在这里记一下原根 Definition 阶 若\(a,p\)互质,且\(p>1\),我们称使\(a^n\equiv 1\ (mod\ p)\ ...

  6. 在线HTTP速度测试(响应时间测试)及浏览器兼容测试

    一.前言 网站的响应时间,是判断一个网站是否是好网站的重要的因素之一.百度首页的响应时间在全国各个省份小于10ms.这个响应时间远远好于竞争对手.根据美丽说的技术负责人分析,美丽说访问速度提升10%, ...

  7. HDU 5682 zxa and leaf 二分 树形dp

    zxa and leaf 题目连接: http://acm.hdu.edu.cn/showproblem.php?pid=5682 Description zxa have an unrooted t ...

  8. Hihocoder #1082 : 然而沼跃鱼早就看穿了一切 暴力

    时间限制:1000ms 单点时限:1000ms 内存限制:256MB 描述 fjxmlhx每天都在被沼跃鱼刷屏,因此他急切的找到了你希望你写一个程序屏蔽所有句子中的沼跃鱼(“marshtomp”,不区 ...

  9. The YubiKey NEO -- Smartcard features

    Smartcard features on the YubiKey NEO YubiKeys are a line of small and low-cost hardware security to ...

  10. C#多线程编程之:lock使用注意事项

    1.避免锁定public类型对象. 如果实例可以被公共访问,将出现lock(this)问题. 如有一个类MyClass,该类有一个Method方法通过lock(this)来实现互斥: 1 public ...