user3085693
user3085693

Reputation: 67

How to extract image file details in Python (Windows)?

I'm writing a program that has to process multiple images. Many of them have different resolutions (dpi). Is there a way to retrieve the information from file properties? I tried PIL.ExifTags, PIL.IptcImagePlugin, other EXIF extractors, but everything returns None.the information I need to retrieve

Upvotes: 1

Views: 1751

Answers (1)

hMatoba
hMatoba

Reputation: 547

If it can't get dpi from jpeg by exif tools, the jpeg may not have exif and may have JFIF(APP0 metadata). It can get dpi from JFIF.

def get_resolution(filename):
    with open(filename, "rb") as f:
        data = f.read()
    if data[0:2] != b"\xff\xd8":
        raise ValueError("Not JPEG.")
    if data[2:4] != b"\xff\xe0":
        return None
    else:
        if data[13] == b"\x00":
            unit = "no unit"
        elif data[13] == b"\x01":
            unit = "dpi"
        elif data[13] == b"\x02":
            unit = "dpcm"
        else:
            raise ValueError("Bad JFIF")
        x = 256 * ord(data[14]) + ord(data[15])
        y = 256 * ord(data[16]) + ord(data[17])
    return {"unit":unit, "resolution":(x, y)}

Upvotes: 1

Related Questions