78 lines
2.2 KiB
Python
78 lines
2.2 KiB
Python
import json
|
|
|
|
import PIL.ExifTags
|
|
from PIL import Image, IptcImagePlugin, TiffImagePlugin
|
|
|
|
|
|
class Exif:
|
|
|
|
def __init__(self, filename: str):
|
|
self.filename = filename
|
|
self.exif = {}
|
|
try:
|
|
self.img = Image.open(self.filename)
|
|
self.img.verify()
|
|
self._readExif()
|
|
self._readIptc()
|
|
except:
|
|
print("Error Couldn't open image: %s" % filename)
|
|
|
|
|
|
def _readExif(self):
|
|
img = self.img._getexif()
|
|
for (key, value) in img.items():
|
|
if key in PIL.ExifTags.TAGS:
|
|
if isinstance(value, TiffImagePlugin.IFDRational):
|
|
value = float(value)
|
|
elif isinstance(value, tuple):
|
|
value = tuple(float(t) if isinstance(t, TiffImagePlugin.IFDRational) else t for t in value)
|
|
elif isinstance(value, bytes):
|
|
value = value.decode(errors="replace")
|
|
self.exif[PIL.ExifTags.TAGS[key]] = value
|
|
return self.exif
|
|
|
|
def _readIptc(self):
|
|
iptcTAGS = {
|
|
(1, 90): 'CodedCharacterSet',
|
|
(2, 0): 'RecordVersion',
|
|
(2, 5): 'ObjectName',
|
|
(2, 25): 'Keywords',
|
|
(2, 55): 'DateCreated',
|
|
(2, 60): 'TimeCreated',
|
|
(2, 62): 'DigitizationDate',
|
|
(2, 63): 'DigitizationTime',
|
|
(2, 80): 'Byline',
|
|
(2, 120): 'Caption',
|
|
}
|
|
img = IptcImagePlugin.getiptcinfo(self.img)
|
|
for (key, value) in img.items():
|
|
decoded = iptcTAGS.get(key, str(key))
|
|
if isinstance(value, list):
|
|
self.exif[decoded] = [x.decode('utf-8') for x in value]
|
|
else:
|
|
self.exif[decoded] = value.decode('utf-8')
|
|
return self.exif
|
|
|
|
def getValue(self, value):
|
|
if self.exif[value]:
|
|
return self.exif[value]
|
|
|
|
def getJson(self):
|
|
return json.dumps(self.exif)
|
|
|
|
def getDic(self):
|
|
return self.exif
|
|
|
|
def __str__(self):
|
|
return self.filename
|
|
|
|
|
|
|
|
xxx = Exif('./photo.jpg')
|
|
|
|
print(xxx.getJson())
|
|
print(xxx.getValue('Keywords'))
|
|
print(xxx.getValue('DateTimeOriginal'))
|
|
print(xxx.getDic())
|
|
print(xxx)
|
|
|