仅仅根据文件后缀判断文件类型显然不准,在python有一个内置模块imghdr可以用来判断图片的真实类型。代码如下:
import imghdr
imgType = imghdr.what(imageFile)
将会输出gif,png,jpeg等图片类型 。其原理是通过读取文件的开头的一段字符进行类型匹配 。具体查看了下代码,imageFile只能是本地文件,不可以是url 远程文件。具体可以个修改下该模块,使其支持远程文件。
使用场景:
经常在抓取一些站点上的图片时,有些站点上的图片直接是不带文件类型的,如:/img/bVksck ,可以通过该模块进行抓取后,为文件增加相应的后缀名,而如果发现抓取的文件不是图片类型文件时进行删除(避免抓到别人修改过的图片木马),以下是一个简单的判断删除示例:
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)