仅仅根据文件后缀判断文件类型显然不准,在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)