python实现批量修改图片格式和尺寸
作者:PassionY 时间:2021-02-12 10:47:35
本文实例为大家分享了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')
来源:https://blog.csdn.net/yupu56/article/details/50569781
标签:python,图片格式,批量修改
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
asp入门之字符串函数介绍示例
2008-11-04 20:18:00
js全选/全不选/反选 checkbox代码
2008-03-18 13:00:00
Rs.Open参数说明
2008-05-12 22:43:00
React TypeScript 应用中便捷使用Redux Toolkit方法详解
2023-08-11 09:48:21
![](https://img.aspxhome.com/file/2023/6/55976_0s.jpg)
18个超棒的Web和移动应用开发框架
2011-03-31 17:04:00
CentOS7服务器中apache、php7以及mysql5.7的安装配置代码
2023-11-19 02:14:52
发一新浪招聘的图片滚动控制JS效果
2011-08-10 19:17:25
详解python使用Nginx和uWSGI来运行Python应用
2023-07-25 20:40:55
php+Memcached实现简单留言板功能示例
2023-11-15 09:30:02
![](https://img.aspxhome.com/file/2023/0/85820_0s.png)
php中的登陆login
2023-10-08 10:49:30
奇淫技巧和西天取经
2009-08-24 12:34:00
有用的:nth-child秘方
2011-07-01 12:56:11
python matplotlib绘图,修改坐标轴刻度为文字的实例
2023-09-29 12:27:57
![](https://img.aspxhome.com/file/2023/7/62897_0s.jpg)
ASP访问统计计数器代码
2008-03-20 13:33:00
一段Asp301重定向过程代码
2010-05-04 16:38:00
asp使用 sql_dmo 给表添加索引
2010-03-17 20:57:00
Pytorch中的Tensorboard与Transforms搭配使用
2023-07-09 08:27:05
![](https://img.aspxhome.com/file/2023/2/62022_0s.png)
PHP扩展之kafka安装应用案例详解
2023-09-06 09:53:43
python取数作为临时极大值(极小值)的方法
2021-02-27 10:32:01
python函数参数(必须参数、可变参数、关键字参数)
2023-09-17 07:54:28