如何通过 EXIF / JFIF 签名检测 JPEG 文件?

Lit*_*ite 1 python exif jfif

几天前,我在另一个领域提出了一个问题,最后一位朋友(@emcconville)帮助我编写了一个“恢复单个文件中的每个 JPEG 文件”的脚本。现在我意识到该程序仅适用于具有标准“JFIF”的图像,并且无法检索具有“EXIF”标准的图像(数码相机拍摄的图像)。

如何更改程序,使其也能知道图像中的Exif标准?我对Python不熟悉,也不知道它的威力。

谢谢

import struct

with open('src.bin', 'rb') as f:
    # Calculate file size.
    f.seek(0, 2)
    total_bytes = f.tell()
    # Rewind to beging.
    f.seek(0)
    file_cursor = f.tell()
    image_cursor = 0

    while file_cursor < total_bytes:
        # Can for start of JPEG.
        if f.read(1) == b"\xFF":
            if f.read(3) == b"\xD8\xFF\xE0":
                print("JPEG FOUND!")
                # Backup and find the size of the image
                f.seek(-8, 1)
                payload_size = struct.unpack('<I', f.read(4))[0]
                # Write image to disk
                d_filename = 'image{0}.jpeg'.format(image_cursor)
                with open(d_filename, 'wb') as d:
                    d.write(f.read(payload_size))
                image_cursor += 1
        file_cursor = f.tell()
Run Code Online (Sandbox Code Playgroud)

Joe*_*Joe 5

EXIF 文件的标记为 0xffe1,JFIF 文件的标记为 0xffe0。因此,所有依赖 0xffe0 来检测 JPEG 文件的代码都将错过所有 EXIF 文件。(从这里)

所以只要改变

if f.read(3) == b"\xD8\xFF\xE0":
Run Code Online (Sandbox Code Playgroud)

if f.read(3) == b"\xD8\xFF\xE1":
Run Code Online (Sandbox Code Playgroud)

如果您想检查这两种情况,请不要.read()再这样使用。相反,像

x = f.read(3)
if x in (b"\xD8\xFF\xE0", b"\xD8\xFF\xE1"):
Run Code Online (Sandbox Code Playgroud)