2019-06-10 14:01:33 955浏览
今天千锋扣丁学堂Python培训老师给大家分享一篇关于如何使用python判断jpeg图片完整性的示例,下面我们一起来看一下吧。
Start Marker | JFIF Marker | Header Length | Identifier 0xff, 0xd8 | 0xff, 0xe0 | 2-bytes | "JFIF\0"
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
from PIL import Image def is_jpg(filename): try: i=Image.open(filename) return i.format =='JPEG' except IOError: return Fals
#coding=utf-8 #summary: 判断图片的有效性 import io import 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')
【关注微信公众号获取更多学习资料】 【扫码进入Python全栈开发免费公开课】