SoFunction
Updated on 2025-03-02

Example of using python to determine the integrity of jpeg image

It is very simple to judge the file format by using an extension, but it may be wrong. The jpeg file has a fixed file header, and the format of its file header is as follows:

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

Therefore, you can quickly determine the file format through the file 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 make judgments through the PIL class library:

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

Application scenario: determine whether the jpeg file in the image folder is complete, the code is as follows:

#coding=utf-8
#summary: To judge the validity of picturesimport io
import os
 
from PIL import Image
#Judge whether the file is a valid (complete) picture#Enter the parameter as file path#There will be misseddef IsValidImage(pathfile):
 bValid = True
 try:
  (pathfile).verify()
 except:
  bValid = False
 return bValid
 
 
def is_valid_jpg(jpg_file): 
  """Judge whether the JPG file download is complete
   """ 
  if jpg_file.split('.')[-1].lower() == 'jpg': 
    with open(jpg_file, 'rb') as f: 
      (-2, 2) 
      return () == '\xff\xd9' #Determine whether jpg contains the end field  else: 
    return True
 
#Use the PIL library to make jpeg format judgment, but some files without end fields cannot be detecteddef is_jpg(filename):
  try:
    i=(filename)
    return  =='JPEG'
  except IOError:
    return False
 
allfiles=('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=('image',i)
		value=IsValidImage(f)
		if not value:
			log_file.write(i+'\n')
		if is_valid_jpg(f):
			print f
			(i+'\n')
		else:
			log_w.write(i+'\n')
		if is_jpg(f):
			(i+'\n')
		else:
			(i+'\n')

The above example of using python to determine the integrity of jpeg images is all the content I have shared with you. I hope you can give you a reference and I hope you can support me more.