-
Notifications
You must be signed in to change notification settings - Fork 143
Expand file tree
/
Copy pathexif_write.py
More file actions
223 lines (196 loc) · 8.62 KB
/
exif_write.py
File metadata and controls
223 lines (196 loc) · 8.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# pyre-ignore-all-errors[5, 21, 24]
from __future__ import annotations
import datetime
import io
import json
import logging
import math
from pathlib import Path
import piexif
LOG = logging.getLogger(__name__)
class ExifEdit:
_filename_or_bytes: str | bytes
def __init__(self, filename_or_bytes: Path | bytes) -> None:
"""Initialize the object"""
if isinstance(filename_or_bytes, Path):
# make sure filename is resolved to avoid to be interpretted as bytes in piexif
# see https://github.com/hMatoba/Piexif/issues/124
self._filename_or_bytes = str(filename_or_bytes.resolve())
else:
self._filename_or_bytes = filename_or_bytes
self._ef: dict = piexif.load(self._filename_or_bytes)
@staticmethod
def decimal_to_dms(
value: float, precision: int
) -> tuple[tuple[float, int], tuple[float, int], tuple[float, int]]:
"""
Convert decimal position to degrees, minutes, seconds in a fromat supported by EXIF
"""
deg = math.floor(value)
min = math.floor((value - deg) * 60)
sec = math.floor((value - deg - min / 60) * 3600 * precision)
return (deg, 1), (min, 1), (sec, precision)
def add_image_description(self, data: dict) -> None:
"""Add a dict to image description."""
self._ef["0th"][piexif.ImageIFD.ImageDescription] = json.dumps(
data, sort_keys=True, separators=(",", ":")
)
def add_orientation(self, orientation: int) -> None:
"""Add image orientation to image."""
if orientation not in range(1, 9):
raise ValueError(f"orientation value {orientation} must be in range(1, 9)")
self._ef["0th"][piexif.ImageIFD.Orientation] = orientation
def add_date_time_original(self, dt: datetime.datetime) -> None:
"""Add date time original."""
self._ef["Exif"][piexif.ExifIFD.DateTimeOriginal] = dt.strftime(
"%Y:%m:%d %H:%M:%S"
)
self._ef["Exif"][piexif.ExifIFD.SubSecTimeOriginal] = dt.strftime("%f")
if dt.tzinfo is not None:
# UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object is naive).
# (empty), +0000, -0400, +1030, +063415, -030712.345216
offset_str = dt.strftime("%z")
if offset_str:
sign, hh, mm = offset_str[0], offset_str[1:3], offset_str[3:5]
assert sign in ["+", "-"], sign
assert hh.isdigit(), hh
assert mm.isdigit(), mm
self._ef["Exif"][piexif.ExifIFD.OffsetTimeOriginal] = f"{sign}{hh}:{mm}"
else:
if piexif.ExifIFD.OffsetTimeOriginal in self._ef["Exif"]:
del self._ef["Exif"][piexif.ExifIFD.OffsetTimeOriginal]
else:
if piexif.ExifIFD.OffsetTimeOriginal in self._ef["Exif"]:
del self._ef["Exif"][piexif.ExifIFD.OffsetTimeOriginal]
def add_gps_datetime(self, dt: datetime.datetime) -> None:
"""Add GPSDateStamp and GPSTimeStamp."""
dt = dt.astimezone(datetime.timezone.utc)
# YYYY:MM:DD
self._ef["GPS"][piexif.GPSIFD.GPSDateStamp] = dt.strftime("%Y:%m:%d")
self._ef["GPS"][piexif.GPSIFD.GPSTimeStamp] = (
(dt.hour, 1),
(dt.minute, 1),
# num / den = (dt.second * 1e6 + dt.microsecond) / 1e6
(int(dt.second * 1e6 + dt.microsecond), int(1e6)),
)
def add_lat_lon(self, lat: float, lon: float, precision: float = 1e7) -> None:
"""Add lat, lon to gps (lat, lon in float)."""
self._ef["GPS"][piexif.GPSIFD.GPSLatitudeRef] = "N" if lat > 0 else "S"
self._ef["GPS"][piexif.GPSIFD.GPSLongitudeRef] = "E" if lon > 0 else "W"
self._ef["GPS"][piexif.GPSIFD.GPSLongitude] = ExifEdit.decimal_to_dms(
abs(lon), int(precision)
)
self._ef["GPS"][piexif.GPSIFD.GPSLatitude] = ExifEdit.decimal_to_dms(
abs(lat), int(precision)
)
def add_altitude(self, altitude: float, precision: int = 100) -> None:
"""Add altitude (pre is the precision)."""
ref = 0 if altitude > 0 else 1
self._ef["GPS"][piexif.GPSIFD.GPSAltitude] = (
int(abs(altitude) * precision),
precision,
)
self._ef["GPS"][piexif.GPSIFD.GPSAltitudeRef] = ref
def add_direction(
self, direction: float, ref: str = "T", precision: int = 100
) -> None:
"""Add image direction."""
# normalize direction
direction = direction % 360.0
self._ef["GPS"][piexif.GPSIFD.GPSImgDirection] = (
int(abs(direction) * precision),
precision,
)
self._ef["GPS"][piexif.GPSIFD.GPSImgDirectionRef] = ref
def add_make(self, make: str) -> None:
if not make:
raise ValueError("Make cannot be empty")
self._ef["0th"][piexif.ImageIFD.Make] = make
def add_model(self, model: str) -> None:
if not model:
raise ValueError("Model cannot be empty")
self._ef["0th"][piexif.ImageIFD.Model] = model
def _safe_dump(self) -> bytes:
TRUSTED_TAGS = [
piexif.ExifIFD.DateTimeOriginal,
piexif.GPSIFD.GPSAltitude,
piexif.GPSIFD.GPSAltitudeRef,
piexif.GPSIFD.GPSImgDirection,
piexif.GPSIFD.GPSImgDirection,
piexif.GPSIFD.GPSImgDirectionRef,
piexif.GPSIFD.GPSImgDirectionRef,
piexif.GPSIFD.GPSLatitude,
piexif.GPSIFD.GPSLatitudeRef,
piexif.GPSIFD.GPSLongitude,
piexif.GPSIFD.GPSLongitudeRef,
piexif.ImageIFD.ImageDescription,
piexif.ImageIFD.Orientation,
]
thumbnail_removed = False
while True:
try:
exif_bytes = piexif.dump(self._ef)
except piexif.InvalidImageDataError as exc:
if thumbnail_removed:
raise exc
LOG.debug(
"InvalidImageDataError on dumping -- removing thumbnail and 1st: %s",
exc,
)
# workaround: https://github.com/hMatoba/Piexif/issues/30
del self._ef["thumbnail"]
del self._ef["1st"]
thumbnail_removed = True
# retry later
except ValueError as exc:
# workaround: https://github.com/hMatoba/Piexif/issues/95
# a sample message: "dump" got wrong type of exif value.\n41729 in Exif IFD. Got as <class 'int'>.
message = str(exc)
if "got wrong type of exif value" in message:
split = message.split("\n")
LOG.debug(
"Found invalid EXIF tag -- removing it and retry: %s", message
)
try:
tag = int(split[1].split()[0])
ifd = split[1].split()[2]
except Exception:
raise exc
if tag in TRUSTED_TAGS:
raise exc
else:
del self._ef[ifd][tag]
# retry later
else:
raise exc
except Exception as exc:
zeroth_ifd = self._ef.get("0th", {})
# workaround: https://github.com/mapillary/mapillary_tools/issues/662
if piexif.ImageIFD.AsShotNeutral in zeroth_ifd:
del zeroth_ifd[piexif.ImageIFD.AsShotNeutral]
assert piexif.ImageIFD.AsShotNeutral not in zeroth_ifd
else:
raise exc
else:
break
return exif_bytes
def dump_image_bytes(self) -> bytes:
exif_bytes = self._safe_dump()
with io.BytesIO() as output:
piexif.insert(exif_bytes, self._filename_or_bytes, output)
return output.read()
def write(self, filename: Path | None = None) -> None:
"""Save exif data to file."""
if filename is None:
if not isinstance(self._filename_or_bytes, str):
raise ValueError("Unable to write image into bytes")
filename = Path(self._filename_or_bytes)
# make sure filename is resolved to avoid to be interpretted as bytes in piexif
filename = filename.resolve()
exif_bytes = self._safe_dump()
if isinstance(self._filename_or_bytes, bytes):
img = self._filename_or_bytes
else:
with open(self._filename_or_bytes, "rb") as fp:
img = fp.read()
piexif.insert(exif_bytes, img, str(filename))