Skip to content

Instantly share code, notes, and snippets.

@Whats-A-MattR
Last active March 11, 2023 05:18
Show Gist options
  • Save Whats-A-MattR/9dcdd8fafbb95acc06d62c8aeb16c5d3 to your computer and use it in GitHub Desktop.
Save Whats-A-MattR/9dcdd8fafbb95acc06d62c8aeb16c5d3 to your computer and use it in GitHub Desktop.
from PIL import Image
from PIL.ExifTags import TAGS
import os
# ask for image path
accepted_exts = ['jpg', 'jpeg', 'png', 'gif']
# exits if path not found
img_path = input('please provide path and hit enter: ')
if not os.path.exists(img_path): exit(f'invalid path provided, cannot find anything at {img_path')
# exits if file isnt of accepted type
else:
if not os.path.splitext(img_path)[1].replace('.', '') in accepted_exts: exit(f'provided file is of type {os.path.splitext(img_path)[1].replace(".", "")}, and not one of the following: {", ".join(accepted_exts)}')
# import image using PIL.Image
image = Image.open(img_path)
# start making our dictionary item
img_dict = {
'filename': image.filename,
'size': image.size,
'height': image.height,
'width': image.width,
'format': image.format,
'mode': image.mode
}
# grab exif data from image
exif_data = image.getexif()
# iterate, and decode if required
for tag_id in exif_data:
tag = TAGS.get(tag_id, tag_id)
data = exif_data.get(tag_id)
if isinstance(data, bytes): data = data.decode()
img_dict[tag] = data
# this just looks nicer than print(img_dict)
for k, v in img_dict.items():
print(f'{k}: {v}')
@Whats-A-MattR
Copy link
Author

Extract MetaData (Exif Data) from an image

This can at times extract information such as gps coordinates of the image, when taken on a gps capable device.
Otherwise, expect to see data such as the date it was taken / modified and by what camera or software respectively

Very simple implementation of pillow, taking user input to get exif data, this can easily be modified to loop over files in a directory

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment