python实现批量修改图片格式和尺寸
本文实例为大家分享了python批量处理图片的具体代码,供大家参考,具体内容如下
公司的一个项目要求把所有4096x4096的图片全部转化成2048x2048的图片,这种批量转换图片大小的软件网上很多,我的同事原来使用的美图看看的批量转换,但是稍微有点麻烦,每次还需要指定要转换的图片的输入路径和输出路径,而且每次都只能处理一个文件夹,很繁琐,于是我想到了万能的Python,然后写了一个脚本来批量处理图片,同一个根目录下的所有文件夹的子文件等的图片全部会处理掉。
代码中还加入了很多的异常捕获机制和提示,希望对大家有帮助。
备注:
1.导入了PIL库,是处理图片用的,很强大;
2.导入了win32库,是判断隐藏文件用的,我们的项目需要删除隐藏文件,不需要的可以直接找到删除。
3.导入send2trash库,是把删除的文件放进垃圾箱,而不是永久删除,这个我只是防止删除有用的文件而搞得,有点严谨了是吧,不需要的可以删掉啊。
4.我这个脚本是Python2.7编写的,但是在处理中文编码的时候非常恶心,尽管最后被我解决了,这个解决的方法,我随后会再单独写一篇,但是此刻我是建议大家不要用2.x版本的python了。据说3.x的版本的已经解决了编码的问题。希望大家听我的建议。
#coding=utf-8
importsys
importos,glob
importplatform
importwin32file,win32con
fromPILimportImage
fromsend2trashimportsend2trash
reload(sys)
sys.setdefaultencoding('utf-8')
#new_width=2048
#width=int(raw_input("thewidthUwant:"))
#imgslist=glob.glob(path+'/*.*')
ShuiPing="水平"
ShiZhuang="矢状"
GuanZhuang="冠状"
defPy_Log(_string):
print"----"+_string.decode('utf-8')+"----"
defis_windows_system():
return'Windows'inplatform.system()
defis_hiden_file(file_Path):
ifis_windows_system():
fileAttr=win32file.GetFileAttributes(file_Path)
iffileAttr&win32con.FILE_ATTRIBUTE_HIDDEN:
returnTrue
returnFalse
returnFalse
defremove_hidden_file(file_path):
send2trash(file_path)
print"Deletehiddenfilepath:"+file_path
defastrcmp(str1,str2):
returnstr1.lower()==str2.lower()
defresize_image(img_path):
try:
mPath,ext=os.path.splitext(img_path)
if(astrcmp(ext,".png")orastrcmp(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("非图片格式")
exceptException,e:
printe
#改变图片类型
defchange_img_type(img_path):
try:
img=Image.open(img_path)
img.save('new_type.png')
exceptException,e:
printe
#处理远程图片
defhandle_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')
exceptException,e:
printe
defrename_forder(forder_path):
Py_Log("------------rename_forder--------------------------")
names=os.path.split(forder_path)
try:
if(unicode(ShuiPing)inunicode(names[1],'gbk')):
os.rename(forder_path,names[0]+"\\"+"01")
Py_Log(names[1]+"-->"+"01")
if(unicode(ShiZhuang)inunicode(names[1],'gbk')):
os.rename(forder_path,names[0]+"\\"+"02")
Py_Log(names[1]+"-->"+"02")
if(unicode(GuanZhuang)inunicode(names[1],'gbk')):
os.rename(forder_path,names[0]+"\\"+"03")
Py_Log(names[1]+"-->"+"03")
exceptException,e:
printe
defBFS_Dir(dirPath,dirCallback=None,fileCallback=None):
queue=[]
ret=[]
queue.append(dirPath);
whilelen(queue)>0:
tmp=queue.pop(0)
if(os.path.isdir(tmp)):
ret.append(tmp)
foriteminos.listdir(tmp):
queue.append(os.path.join(tmp,item))
ifdirCallback:
dirCallback(tmp)
elif(os.path.isfile(tmp)):
ret.append(tmp)
iffileCallback:
fileCallback(tmp)
returnret
defDFS_Dir(dirPath,dirCallback=None,fileCallback=None):
stack=[]
ret=[]
stack.append(dirPath);
whilelen(stack)>0:
tmp=stack.pop(len(stack)-1)
if(os.path.isdir(tmp)):
ret.append(tmp)
foriteminos.listdir(tmp):
stack.append(os.path.join(tmp,item))
ifdirCallback:
dirCallback(tmp)
elif(os.path.isfile(tmp)):
ret.append(tmp)
iffileCallback:
fileCallback(tmp)
returnret
defprintDir(dirPath):
print"dir:"+dirPath
if(is_hiden_file(dirPath)):
remove_hidden_file(dirPath)
else:
rename_forder(dirPath)
defprintFile(dirPath):
print"file:"+dirPath
resize_image(dirPath)
returnTrue
if__name__=='__main__':
whileTrue:
path=raw_input("Path:")
new_width=int(raw_input("thewidthUwant:"))
try:
b=BFS_Dir(path,printDir,printFile)
Py_Log("\r\n**********\r\n"+"*********图片处理完毕*********"+"\r\n**********\r\n")
except:
print"Unexpectederror:",sys.exc_info()
raw_input('pressenterkeytorehandle')
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。