1、分析:
以16进制打开几种常见图片格式,可以看到文件类型都标注在前面十几个字节内。
几种常见格式的前16个字节内容是这样的:
.png 89 50 4E 47 0D 0A 1A 0A 00 00 00 0D 49 48 44 52
.bmp 42 4D 6A 74 00 00 00 00 00 00 36 00 00 00 28 00
.jpg jpeg FF D8 FF E0 00 10 4A 46 49 46 00 01 01 01 00 60
.gif 47 49 46 38 39 61 90 01 90 01 F7 FF 00 05 05 05
2、代码如下:
把上面的内容放在字典中,以图片的前16字节作为“键”,以文件类型作为“值”
传人图片路径,返回文件类型(.***)
def identify_pic_type(path):
with open(path,'rb') as f:
file = f.read(16).hex() #.hex()方法以字符串输出16进制数, 读取文件的前16个字节。
pic_type_lib = {
'ffd8ffe000104a464946000101010060':'.jpg',
'89504e470d0a1a0a0000000d49484452': '.png',
'47494638396190019001f7ff00050505': '.gif',
'424d6a74000000000000360000002800': '.bmp'
}
return pic_type_lib[file]
path = r'C:\Users\yylwin10\Desktop\bmp'
pic_type = identify_pic_type(path)
print('the pic type is %s'%pic_type)
执行结果:
the pic type is .bmp