Python - How to list tags from jpg EXIF data?

2k views Asked by At

I've got a bunch of images I'm planning to use for something, and it would be very helpful if I could sort them all by giving them tags that a Python script can read. I tried a few methods from this StackOverflow post, but none of them return the data I need. Here's what I've tried:

from PIL import Image
import PIL.ExifTags
import exifread

dir = "C:\directory\\"
image = "image_name.jpg"
image_dir = dir + image
img = Image.open(image_dir)

#Attempt 1 - using PIL
exif_data = img._getexif()

print(exif_data)

#Attempt 2 - using exifread
f = open(image_dir)
tags = exifread.process_file(f)

print(tags)

#Attemp 3 - using PIL
exif = {
    PIL.ExifTags.TAGS[k]: v
    for k, v in img._getexif().items()
    if k in PIL.ExifTags.TAGS
}

print(exif)

The results are a bit long and messy (Attempt 1 returns a very long dictionary with a bunch of repeating "\x00\" so I won't post that here):

  • Attempt 2 - {'Image XPKeywords': (0x9C9E) Byte=[] @ 30, 'EXIF Padding': (0xEA1C) Undefined=[] @ 2128, 'Image ExifOffset': (0x8769) Long=2110 @ 18, 'Image Padding': (0xEA1C) Undefined=[] @ 50}
  • Attempt 3 - {'ExifOffset': 2110, 'XPKeywords': 'e\x00x\x00a\x00m\x00p\x00l\x00e\x00;\x00t\x00e\x00s\x00t\x00\x00\x00'}

The tags themselves are "example" and "test." Any tips on what I can do differently?

1

There are 1 answers

0
Jim Factor On

You might want to try running this as a Python 3 script. I just ran your attempt #1 code against

https://upload.wikimedia.org/wikipedia/commons/1/1e/Stonehenge.jpg

and it worked, giving the results:

{40963: 472, 305: 'Adobe Photoshop CS Windows', 274: 1, 40962: 709, 40961: 65535, 296: 2, 34665: 164, 282: (120, 1), 283: (120, 1), 306: '2005:10:13 15:32:07'}

Note: I was using Pillow, the fork of PIL from - http://pillow.readthedocs.io/en/3.1.x/installation.html