python 判断图片的类型

python 判断图片的类型,第1张

仅仅根据文件后缀判断文件类型显然不准,在python有一个内置模块imghdr可以用来判断图片的真实类型。


代码如下:

import imghdr

imgType = imghdr.what(imageFile)

将会输出gif,png,jpeg等图片类型 。


其原理是通过读取文件的开头的一段字符进行类型匹配 。


具体查看了下代码,imageFile只能是本地文件,不可以是url 远程文件。


具体可以个修改下该模块,使其支持远程文件。


import imghdr,os


 
#filename = 'img.py'


 
filename = 'bVksck'


 
imgType = imghdr.what(filename)


 
if imgType:


 
print imgType


 
newName = (filename + '.' + imgType)


 
os.rename(filename,newName)


 
else:


 
print 'the file is not a pic,rm it now'


 
os.remove(filename)

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/568622.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-09
下一篇 2022-04-09

发表评论

登录后才能评论

评论列表(0条)

保存