Python 批量修改图片格式和尺寸
公司的一个项目要求把所有4096x4096的图片全部转化成2048x2048的图片,这种批量转换图片大小的软件网上很多,我的同事原来使用的美图看看的批量转换,但是稍微有点麻烦,每次还需要指定要转换的图片的输入路径和输出路径,而且每次都只能处理一个文件夹,很繁琐,于是我想到了万能的Python,然后写了一个脚本来批量处理图片,同一个根目录下的所有文件夹的子文件等的图片全部会处理掉。
代码中还加入了很多的异常捕获机制和提示,希望对大家有帮助。
备注:
1.导入了PIL库,是处理图片用的,很强大;
2.导入了win32库,是判断隐藏文件用的,我们的项目需要删除隐藏文件,不需要的可以直接找到删除。
3.导入send2trash库,是把删除的文件放进垃圾箱,而不是永久删除,这个我只是防止删除有用的文件而搞得,有点严谨了是吧,不需要的可以删掉啊。
4.我这个脚本是Python2.7编写的,但是在处理中文编码的时候非常恶心,尽管最后被我解决了,这个解决的方法,我随后会再单独写一篇,但是此刻我是建议大家不要用2.x版本的python 了。据说3.x的版本的已经解决了编码的问题。希望大家听我的建议。
- #coding=utf-8
- import sys
- import os, glob
- import platform
- import win32file,win32con
- from PIL import Image
- from send2trash import send2trash
- reload(sys)
- sys.setdefaultencoding('utf-8')
- #new_width =2048
- #width =int(raw_input("the width U want:"))
- #imgslist = glob.glob(path+'/*.*')
- ShuiPing="水平"
- ShiZhuang="矢状"
- GuanZhuang="冠状"
- def Py_Log(_string):
- print "----"+_string.decode('utf-8')+"----"
- def is_windows_system():
- return 'Windows' in platform.system()
- def is_hiden_file(file_Path):
- if is_windows_system():
- fileAttr = win32file.GetFileAttributes(file_Path)
- if fileAttr & win32con.FILE_ATTRIBUTE_HIDDEN :
- return True
- return False
- return False
- def remove_hidden_file(file_path):
- send2trash(file_path)
- print "Delete hidden file path:"+file_path
- def astrcmp(str1,str2):
- return str1.lower()==str2.lower()
- def resize_image(img_path):
- try:
- mPath, ext = os.path.splitext(img_path)
- if (astrcmp(ext,".png") or astrcmp(ext,".jpg")):
- img = Image.open(img_path)
- (width,height) = img.size
- if(width != 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("非图片格式")
- except Exception,e:
- print e
- #改变图片类型
- def change_img_type(img_path):
- try:
- img = Image.open(img_path)
- img.save('new_type.png')
- except Exception,e:
- print e
- #处理远程图片
- def handle_remote_img(img_url):
- try:
- request = urllib2.Request(img_url)
- img_data = urllib2.urlopen(request).read()
- img_buffer = StringIO.StringIO(img_data)
- img = Image.open(img_buffer)
- img.save('remote.jpg')
- (width,height) = img.size
- out = img.resize((200,height * 200 / width),Image.ANTIALIAS)
- out.save('remote_small.jpg')
- except Exception,e:
- print e
- def rename_forder(forder_path):
- Py_Log("------------rename_forder--------------------------")
- names = os.path.split(forder_path)
- try:
- if(unicode(ShuiPing) in unicode(names[1],'gbk')):
- os.rename(forder_path,names[0]+"\\"+"01")
- Py_Log(names[1]+"-->"+"01")
- if(unicode(ShiZhuang) in unicode(names[1],'gbk')):
- os.rename(forder_path,names[0]+"\\"+"02")
- Py_Log(names[1]+"-->"+"02")
- if(unicode(GuanZhuang) in unicode(names[1],'gbk')):
- os.rename(forder_path,names[0]+"\\"+"03")
- Py_Log(names[1]+"-->"+"03")
- except Exception,e:
- print e
- def BFS_Dir(dirPath, dirCallback = None, fileCallback = None):
- queue = []
- ret = []
- queue.append(dirPath);
- while len(queue) > 0:
- tmp = queue.pop(0)
- if(os.path.isdir(tmp)):
- ret.append(tmp)
- for item in os.listdir(tmp):
- queue.append(os.path.join(tmp, item))
- if dirCallback:
- dirCallback(tmp)
- elif(os.path.isfile(tmp)):
- ret.append(tmp)
- if fileCallback:
- fileCallback(tmp)
- return ret
- def DFS_Dir(dirPath, dirCallback = None, fileCallback = None):
- stack = []
- ret = []
- stack.append(dirPath);
- while len(stack) > 0:
- tmp = stack.pop(len(stack) - 1)
- if(os.path.isdir(tmp)):
- ret.append(tmp)
- for item in os.listdir(tmp):
- stack.append(os.path.join(tmp, item))
- if dirCallback:
- dirCallback(tmp)
- elif(os.path.isfile(tmp)):
- ret.append(tmp)
- if fileCallback:
- fileCallback(tmp)
- return ret
- def printDir(dirPath):
- print "dir: " + dirPath
- if(is_hiden_file(dirPath)):
- remove_hidden_file(dirPath)
- else:
- rename_forder(dirPath)
- def printFile(dirPath):
- print "file: " + dirPath
- resize_image(dirPath)
- return True
- if __name__ == '__main__':
- while True:
- path = raw_input("Path:")
- new_width =int(raw_input("the width U want:"))
- try:
- b = BFS_Dir(path , printDir, printFile)
- Py_Log ("\r\n **********\r\n"+"*********图片处理完毕*********"+"\r\n **********\r\n")
- except:
- print "Unexpected error:", sys.exc_info()
- raw_input('press enter key to rehandle')
Python 批量修改图片格式和尺寸的更多相关文章
- Python批量修改图片格式和尺寸
Python批量修改图片格式和尺寸 备注: 1.导入了PIL库,是处理图片用的,很强大; 2.导入了的win32库,是判断隐藏文件用的,我们的项目需要删除隐藏文件,不需要的可以直接找到删除. 3.导入 ...
- python批量修改图片名称
import os class BatchRename(): def rename(self): # windows环境 """ os.rename() 方法用于命名文件 ...
- python 批量修改图片大小
一个文件夹下面有好多图片格式是jpg大小是1920*1080,把它们处理成1280*720并按原先图片的名保存在另一路径下这里首先要找到给定路径下所有的图片文件,然后在修改图片文件的大小,这里用到PI ...
- python 批量更换图片格式脚本
问题:将某文件下的所有jpg的图片更换为png的图片 简单的实现: # -*- coding:utf-8 -*- from os.path import splitext import glob fr ...
- python:批量修改文件名批量修改图片尺寸
批量修改文件名 参考博客:https://www.cnblogs.com/zf-blog/p/7880126.html 功能:批量修改文件名 1 2 3 4 5 6 7 8 9 10 11 12 1 ...
- 使用Adobe Photoshop CC 2015批量修改图片尺寸
最近在工作中遇到一个问题,当时客户给的图片尺寸与我要求的图片不符,由于图片非常的多,如果一张一张的修改,十分的麻烦,后来经过一位同事的指点,发现Adobe Photoshop CC 2015可以实现批 ...
- python 将png图片格式转换生成gif动画
先看知乎上面的一个连接 用Python写过哪些[脑洞大开]的小工具? https://www.zhihu.com/question/33646570/answer/157806339 这个哥们通过爬气 ...
- 【faster-rcnn】训练自己的数据——修改图片格式、类别
修改图片格式 matlab代码 其实内部一些代码是用了rbg的fast-rcnn代码的. \datasets\VOCdevkit2007\VOCcode\VOCinit.m里面,查找'jpg',改成' ...
- 利用python批量修改word文件名的方法示例
利用python批量修改word文件名的方法示例 最近不小心把硬盘给格式化了,由于当时的文件没有备份,所以一下所有的文件都没有了,于是只能采取补救措施,用文件恢复软件恢复了一部分的数据出来,但是恢复完 ...
随机推荐
- [python 源码]字符串对象的实现
还是带着问题上路吧,和整数对象的实现同样的问题: >>> a='abc' >>> b='abc' >>> a is b True >> ...
- 八皇后II
用一个数组state记录已经选择的每一行皇后所在的位置,DFS count = 0 N = 8 state = [0]*N def dfs(row): global count for col in ...
- Django的Form机制小问题
使用Django,我们可以以声明式的方式来定义一个Form,如下: 1 2 3 4 5 # -*- coding: utf-8 -*- from django import forms class S ...
- QQ邮件定时发送天气预报
1.首先利用request库去请求数据,天气预报使用的是和风天气的API(www.heweather.com/douments/api/s6/weather-forecast) 2.利用python的 ...
- 时间插件datetimepicker
相关datetimepicker用法查看官网http://eonasdan.github.io/bootstrap-datetimepicker/ {% load staticfiles %} < ...
- 当你的静态资源CDN挂掉了该怎么办?
都知道使用静态的CDN引入jQuery等一些js包的时候,会提升网页的性能,那么,如果你引入CDN的地址挂掉了,那么项目同样也会挂掉,所以我们需要在引入的时候添加一个判断.如下: <script ...
- 数据准备<5>:变量筛选-实战篇
在上一篇文章<数据准备<4>:变量筛选-理论篇>中,我们介绍了变量筛选的三种方法:基于经验的方法.基于统计的方法和基于机器学习的方法,本文将介绍后两种方法在Python(skl ...
- 关于mysql_connect CLIENT_MULTI_RESULTS
自己写了一个mysql存储过程,以为php有用于调用存储过程的内建函数,查了一下发现只能用mysql_query(call pro())这样的方式,我认为从本质上也就相当于在mysql命令行里执行语句 ...
- hdu 4859 最小割
链接:点我 未懂
- JAVA基础(一) ——— static 关键字
1. 静态代码块 保证只创建一次,提升属性的级别为类变量.初始化后独自占用一块内存 2. 静态代码块执行触发条件 (1).当创建这个类的实例 (2).当调用这个类的静态变量 (3).当调用这个类的 ...