使用python判断jpeg图片的完整性实例
用扩展名判断文件格式非常简单,但是有可能是错误的。 jpeg文件有固定的文件头,其文件头的格式如下:
|
1
2
3
|
start marker | jfif marker | header length | identifier 0xff, 0xd8 | 0xff, 0xe0 | 2-bytes | "jfif\0" |
所以可以通过文件头的方式快速判断文件格式:
|
1
2
3
4
5
6
7
|
def is_jpg(filename): data = open(filename,'rb').read(11) if data[:4] != '\xff\xd8\xff\xe0' and data[:4]!='\xff\xd8\xff\xe1': return false if data[6:] != 'jfif\0' and data[6:] != 'exif\0': return false return true |
也可以通过pil类库来做判断:
|
1
2
3
4
5
6
7
|
from pil import imagedef is_jpg(filename): try: i=image.open(filename) return i.format =='jpeg' except ioerror: return fals |
应用场景:判断image文件夹中的jpeg文件是否完整,代码如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
#coding=utf-8#summary: 判断图片的有效性import ioimport os from pil import image#判断文件是否为有效(完整)的图片#输入参数为文件路径#会出现漏检的情况def isvalidimage(pathfile): bvalid = true try: image.open(pathfile).verify() except: bvalid = false return bvalid def is_valid_jpg(jpg_file): """判断jpg文件下载是否完整 """ if jpg_file.split('.')[-1].lower() == 'jpg': with open(jpg_file, 'rb') as f: f.seek(-2, 2) return f.read() == '\xff\xd9' #判定jpg是否包含结束字段 else: return true #利用pil库进行jpeg格式判定,但有些没有结束字段的文件检测不出来def is_jpg(filename): try: i=image.open(filename) return i.format =='jpeg' except ioerror: return false allfiles=os.listdir('image')log_file=open('img_lossinfo.txt','w')log = open('img_r.txt','w')log_w=open('img_w.txt','w')log1=open('img_jpeg.txt','w')log2=open('img_notjpg.txt','w')for i in allfiles:#if 1: if i[-4:]=='.jpg': f=os.path.join('image',i) value=isvalidimage(f) if not value: log_file.write(i+'\n') if is_valid_jpg(f): print f log.write(i+'\n') else: log_w.write(i+'\n') if is_jpg(f): log1.write(i+'\n') else: log2.write(i+'\n') |
原文链接:https://blog.csdn.net/qiyuanxiong/article/details/77943578
本文来自博客园,作者:海_纳百川,转载请注明原文链接:https://www.cnblogs.com/chentiao/p/16337070.html,如有侵权联系删除

浙公网安备 33010602011771号