analitics

Pages

Tuesday, March 26, 2024

Python 3.12.1 : Read EXIF data with PIL.

This is a simple source code I created to read EXIF date from a photo.
import sys
import PIL
import PIL.Image as PILimage
from PIL import ImageDraw, ImageFont, ImageEnhance
from PIL.ExifTags import TAGS, GPSTAGS

class EXIF(object):
    def __init__(self, img):
        self.img = img
        self.exif_data = self.get_exif_data()
        self.lat = self.get_lat()
        self.lon = self.get_lon()
        self.date =self.get_date_time()
        super(Worker, self).__init__()

    @staticmethod
    def get_if_exist(data, key):
        if key in data:
            return data[key]
        return None

    def get_exif_data(self):
        """Returns a dictionary from the exif data of an PIL Image item. Also
        converts the GPS Tags"""
        exif_data = {}
        info = self.img._getexif()
        if info:
            for tag, value in info.items():
                decoded = TAGS.get(tag, tag)
                if decoded == "GPSInfo":
                    gps_data = {}
                    for t in value:
                        sub_decoded = GPSTAGS.get(t, t)
                        gps_data[sub_decoded] = value[t]

                    exif_data[decoded] = gps_data
                else:
                    exif_data[decoded] = value
        print('exif_data ===')
        print(exif_data)
        print('exif_data ===')
        return exif_data

if __name__ == '__main__':
    try:
        img = PILimage.open(sys.argv[1])
        image = EXIF(img)

    except Exception as e:
        print(e)
The result of running source code is this:
python detect_exif_data_001.py paint.jpg
exif_data ===
{'ResolutionUnit': 2, 'ExifOffset': 196, 'Make': 'Canon', 'Model': '', 'Orientation': 1, 
'DateTime': '2012:08:19 13:20:09', 'YCbCrPositioning': 1, 'XResolution': 180.0, 'YResolution': 180.0, 
'ExifVersion': b'0220', 'ComponentsConfiguration': b'\x01\x02\x03\x00', 'CompressedBitsPerPixel': 5.0, 
'DateTimeOriginal': '2012:08:19 13:20:09', 'DateTimeDigitized': '2012:08:19 13:20:09', 'ShutterSpeedValue': 4.3125,
'ApertureValue': 2.75, 'ExposureBiasValue': 0.0, 'MaxApertureValue': 2.75, 'MeteringMode': 5, 'Flash': 16, 
'FocalLength': 5.8, 'UserComment':
...
 'ColorSpace': 1, 'ExifImageWidth': 3072, 'FocalPlaneXResolution': 13653.333333333334, 'ExifImageHeight': 1728,
 'FocalPlaneYResolution': 10224.852071005917, 'FocalPlaneResolutionUnit': 2, 'SensingMethod': 2, 'FileSource': b'\x03',
 'ExposureTime': 0.05, 'ExifInteroperabilityOffset': 3334, 'FNumber': 2.6, 'CustomRendered': 0, 'ISOSpeedRatings': 80,
 'ExposureMode': 0, 'FlashPixVersion': b'0100', 'WhiteBalance': 0, 'DigitalZoomRatio': 1.0, 'SceneCaptureType': 1,
 'MakerNote' ...