Use python to judge the integrity of jpeg pictures

  • 2021-06-28 09:30:08
  • OfStack

Determining the file format with an extension is straightforward, but it can be incorrect.The jpeg file has a fixed header format as follows:


Start Marker | JFIF Marker | Header Length | Identifier
 
0xff, 0xd8  | 0xff, 0xe0 |  2-bytes  | "JFIF\0"

So you can quickly determine the file format by the header:


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

You can also use the PIL class library to make a decision:


from PIL import Image
def is_jpg(filename):
  try:
    i=Image.open(filename)
    return i.format =='JPEG'
  except IOError:
    return Fals

Scenario: Determine if the jpeg file in the image folder is complete with the following code:


#coding=utf-8
#summary:  Judging the validity of pictures 
import io
import os
 
from PIL import Image
# Picture that determines whether the file is valid (complete) 
# Input parameter is file path 
# Leakage will occur 
def IsValidImage(pathfile):
 bValid = True
 try:
  Image.open(pathfile).verify()
 except:
  bValid = False
 return bValid
 
 
def is_valid_jpg(jpg_file): 
  """ judge JPG Is the file download complete  
  """ 
  if jpg_file.split('.')[-1].lower() == 'jpg': 
    with open(jpg_file, 'rb') as f: 
      f.seek(-2, 2) 
      return f.read() == '\xff\xd9' # determine jpg Include end field or not  
  else: 
    return True
 
# utilize PIL Library Processing jpeg Format decision, but some files with no end field cannot be detected 
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')


Related articles: