| 1 |
import io |
| 2 |
import os |
| 3 |
import re |
| 4 |
import struct |
| 5 |
from collections import OrderedDict |
| 6 |
from decimal import Decimal |
| 7 |
from typing import BinaryIO, NamedTuple, Protocol, Tuple, Union, runtime_checkable |
| 8 |
from urllib.error import HTTPError |
| 9 |
from urllib.request import Request, urlopen |
| 10 |
|
| 11 |
from xml.etree import ElementTree |
| 12 |
|
| 13 |
_UNIT_KM = -3 |
| 14 |
_UNIT_100M = -2 |
| 15 |
_UNIT_10M = -1 |
| 16 |
_UNIT_1M = 0 |
| 17 |
_UNIT_10CM = 1 |
| 18 |
_UNIT_CM = 2 |
| 19 |
_UNIT_MM = 3 |
| 20 |
_UNIT_0_1MM = 4 |
| 21 |
_UNIT_0_01MM = 5 |
| 22 |
_UNIT_UM = 6 |
| 23 |
_UNIT_INCH = 6 |
| 24 |
|
| 25 |
_TIFF_TYPE_SIZES = { |
| 26 |
1: 1, |
| 27 |
2: 1, |
| 28 |
3: 2, |
| 29 |
4: 4, |
| 30 |
5: 8, |
| 31 |
6: 1, |
| 32 |
7: 1, |
| 33 |
8: 2, |
| 34 |
9: 4, |
| 35 |
10: 8, |
| 36 |
11: 4, |
| 37 |
12: 8, |
| 38 |
} |
| 39 |
|
| 40 |
_HEIF_BRANDS = { |
| 41 |
b'avif', b'avis', |
| 42 |
b'heic', b'heix', b'hevc', b'hevx', |
| 43 |
b'mif1', b'msf1', |
| 44 |
} |
| 45 |
|
| 46 |
_HEIF_IROT_TO_EXIF = { |
| 47 |
0: 1, |
| 48 |
1: 6, |
| 49 |
2: 3, |
| 50 |
3: 8, |
| 51 |
} |
| 52 |
|
| 53 |
_JPEG_NO_SOF_MARKERS = {0xc4, 0xc8, 0xcc} |
| 54 |
_HTTP_INITIAL_RANGE_SIZE = 8 * 1024 |
| 55 |
_HTTP_RANGE_BLOCK_SIZE = 64 * 1024 |
| 56 |
_HTTP_RANGE_CACHE_BLOCKS = 8 |
| 57 |
_CONTENT_RANGE_RE = re.compile(r"bytes (\d+)-(\d+)/(\d+)$", re.IGNORECASE) |
| 58 |
|
| 59 |
|
| 60 |
@runtime_checkable |
| 61 |
class ReadSeekBinary(Protocol): |
| 62 |
def read(self, size: int = -1) -> bytes: |
| 63 |
... |
| 64 |
|
| 65 |
def seek(self, offset: int, whence: int = 0) -> int: |
| 66 |
... |
| 67 |
|
| 68 |
|
| 69 |
PathInput = Union[str, bytes, os.PathLike] |
| 70 |
FileInput = Union[PathInput, BinaryIO, ReadSeekBinary] |
| 71 |
|
| 72 |
|
| 73 |
class ImageInfo(NamedTuple): |
| 74 |
width: int = -1 |
| 75 |
height: int = -1 |
| 76 |
rotation: int = -1 |
| 77 |
xdpi: int = -1 |
| 78 |
ydpi: int = -1 |
| 79 |
colors: int = -1 |
| 80 |
channels: int = -1 |
| 81 |
|
| 82 |
|
| 83 |
class _ImageMetadata(NamedTuple): |
| 84 |
width: int = -1 |
| 85 |
height: int = -1 |
| 86 |
rotation: int = -1 |
| 87 |
xdpi: int = -1 |
| 88 |
ydpi: int = -1 |
| 89 |
colors: int = -1 |
| 90 |
channels: int = -1 |
| 91 |
|
| 92 |
|
| 93 |
class _HttpRangeReader: |
| 94 |
"""Small seekable HTTP reader backed by validated byte-range requests.""" |
| 95 |
|
| 96 |
def __init__(self, url): |
| 97 |
self.url = url |
| 98 |
self._position = 0 |
| 99 |
self._size = None |
| 100 |
self._validator = None |
| 101 |
self._blocks = OrderedDict() |
| 102 |
self._fallback = None |
| 103 |
self.closed = False |
| 104 |
|
| 105 |
def _request(self, start=None, end=None): |
| 106 |
headers = {"Accept-Encoding": "identity"} |
| 107 |
if start is not None: |
| 108 |
headers["Range"] = "bytes={}-{}".format(start, end) |
| 109 |
if self._validator: |
| 110 |
headers["If-Range"] = self._validator |
| 111 |
try: |
| 112 |
return urlopen(Request(self.url, headers=headers)) |
| 113 |
except HTTPError as error: |
| 114 |
error.close() |
| 115 |
raise |
| 116 |
|
| 117 |
@staticmethod |
| 118 |
def _response_status(response): |
| 119 |
return getattr(response, "status", response.getcode()) |
| 120 |
|
| 121 |
@staticmethod |
| 122 |
def _response_validator(response): |
| 123 |
etag = response.headers.get("ETag") |
| 124 |
if etag and not etag.startswith("W/"): |
| 125 |
return etag |
| 126 |
return response.headers.get("Last-Modified") |
| 127 |
|
| 128 |
def _download_full(self): |
| 129 |
with self._request() as response: |
| 130 |
if self._response_status(response) != 200: |
| 131 |
raise ValueError("Server did not provide a complete response") |
| 132 |
data = response.read() |
| 133 |
self._blocks.clear() |
| 134 |
self._fallback = io.BytesIO(data) |
| 135 |
self._size = len(data) |
| 136 |
self._validator = None |
| 137 |
|
| 138 |
def _load_block(self, block_index): |
| 139 |
if self._fallback is not None: |
| 140 |
return |
| 141 |
block = self._blocks.get(block_index) |
| 142 |
block_start = block_index * _HTTP_RANGE_BLOCK_SIZE |
| 143 |
offset = self._position - block_start |
| 144 |
if block is not None and offset < len(block): |
| 145 |
self._blocks.move_to_end(block_index) |
| 146 |
return |
| 147 |
|
| 148 |
start = block_start + (len(block) if block is not None else 0) |
| 149 |
if self._size is not None and start >= self._size: |
| 150 |
if block is None: |
| 151 |
self._blocks[block_index] = b"" |
| 152 |
return |
| 153 |
if block_index == 0 and block is None: |
| 154 |
end = _HTTP_INITIAL_RANGE_SIZE - 1 |
| 155 |
else: |
| 156 |
end = block_start + _HTTP_RANGE_BLOCK_SIZE - 1 |
| 157 |
|
| 158 |
with self._request(start, end) as response: |
| 159 |
status = self._response_status(response) |
| 160 |
data = response.read() |
| 161 |
validator = self._response_validator(response) |
| 162 |
content_range = response.headers.get("Content-Range", "") |
| 163 |
|
| 164 |
if status == 200: |
| 165 |
self._blocks.clear() |
| 166 |
self._fallback = io.BytesIO(data) |
| 167 |
self._size = len(data) |
| 168 |
self._validator = None |
| 169 |
return |
| 170 |
|
| 171 |
matched = _CONTENT_RANGE_RE.fullmatch(content_range.strip()) if status == 206 else None |
| 172 |
if not matched: |
| 173 |
self._download_full() |
| 174 |
return |
| 175 |
|
| 176 |
response_start, response_end, total = (int(value) for value in matched.groups()) |
| 177 |
if (response_start != start or response_end < response_start or |
| 178 |
response_end > end or len(data) != response_end - response_start + 1): |
| 179 |
self._download_full() |
| 180 |
return |
| 181 |
if self._size is not None and self._size != total: |
| 182 |
self._download_full() |
| 183 |
return |
| 184 |
if self._validator is not None and validator is not None and validator != self._validator: |
| 185 |
self._download_full() |
| 186 |
return |
| 187 |
|
| 188 |
self._size = total |
| 189 |
if self._validator is None: |
| 190 |
self._validator = validator |
| 191 |
self._blocks[block_index] = (block or b"") + data |
| 192 |
self._blocks.move_to_end(block_index) |
| 193 |
while len(self._blocks) > _HTTP_RANGE_CACHE_BLOCKS: |
| 194 |
self._blocks.popitem(last=False) |
| 195 |
|
| 196 |
def read(self, size=-1): |
| 197 |
if self.closed: |
| 198 |
raise ValueError("I/O operation on closed HTTP reader") |
| 199 |
if size == 0: |
| 200 |
return b"" |
| 201 |
if self._fallback is not None: |
| 202 |
self._fallback.seek(self._position) |
| 203 |
data = self._fallback.read(size) |
| 204 |
self._position += len(data) |
| 205 |
return data |
| 206 |
|
| 207 |
self._load_block(self._position // _HTTP_RANGE_BLOCK_SIZE) |
| 208 |
if self._fallback is not None: |
| 209 |
return self.read(size) |
| 210 |
if size < 0: |
| 211 |
size = max(0, self._size - self._position) |
| 212 |
elif self._size is not None: |
| 213 |
size = min(size, max(0, self._size - self._position)) |
| 214 |
|
| 215 |
chunks = [] |
| 216 |
remaining = size |
| 217 |
while remaining > 0: |
| 218 |
block_index = self._position // _HTTP_RANGE_BLOCK_SIZE |
| 219 |
self._load_block(block_index) |
| 220 |
if self._fallback is not None: |
| 221 |
self._fallback.seek(self._position) |
| 222 |
chunk = self._fallback.read(remaining) |
| 223 |
else: |
| 224 |
block = self._blocks[block_index] |
| 225 |
offset = self._position % _HTTP_RANGE_BLOCK_SIZE |
| 226 |
chunk = block[offset:offset + remaining] |
| 227 |
if not chunk: |
| 228 |
break |
| 229 |
chunks.append(chunk) |
| 230 |
self._position += len(chunk) |
| 231 |
remaining -= len(chunk) |
| 232 |
return b"".join(chunks) |
| 233 |
|
| 234 |
def readline(self, size=-1): |
| 235 |
result = bytearray() |
| 236 |
while size < 0 or len(result) < size: |
| 237 |
value = self.read(1) |
| 238 |
if not value: |
| 239 |
break |
| 240 |
result += value |
| 241 |
if value == b"\n": |
| 242 |
break |
| 243 |
return bytes(result) |
| 244 |
|
| 245 |
def seek(self, offset, whence=0): |
| 246 |
if self.closed: |
| 247 |
raise ValueError("I/O operation on closed HTTP reader") |
| 248 |
if whence == os.SEEK_SET: |
| 249 |
position = offset |
| 250 |
elif whence == os.SEEK_CUR: |
| 251 |
position = self._position + offset |
| 252 |
elif whence == os.SEEK_END: |
| 253 |
if self._size is None: |
| 254 |
self._load_block(0) |
| 255 |
position = self._size + offset |
| 256 |
else: |
| 257 |
raise ValueError("invalid whence") |
| 258 |
if position < 0: |
| 259 |
raise ValueError("negative seek position") |
| 260 |
self._position = position |
| 261 |
return position |
| 262 |
|
| 263 |
def tell(self): |
| 264 |
return self._position |
| 265 |
|
| 266 |
def close(self): |
| 267 |
self.closed = True |
| 268 |
self._blocks.clear() |
| 269 |
if self._fallback is not None: |
| 270 |
self._fallback.close() |
| 271 |
|
| 272 |
|
| 273 |
def _open_file(filepath: FileInput): |
| 274 |
if isinstance(filepath, str): |
| 275 |
if filepath.startswith(("http://", "https://")): |
| 276 |
return _HttpRangeReader(filepath), True |
| 277 |
return open(filepath, 'rb'), True |
| 278 |
if isinstance(filepath, (bytes, os.PathLike)): |
| 279 |
return open(filepath, 'rb'), True |
| 280 |
if isinstance(filepath, ReadSeekBinary): |
| 281 |
return filepath, False |
| 282 |
return open(filepath, 'rb'), True |
| 283 |
|
| 284 |
|
| 285 |
def _convertToDPI(density, unit): |
| 286 |
if unit == _UNIT_KM: |
| 287 |
return int(density * 0.0000254 + 0.5) |
| 288 |
elif unit == _UNIT_100M: |
| 289 |
return int(density * 0.000254 + 0.5) |
| 290 |
elif unit == _UNIT_10M: |
| 291 |
return int(density * 0.00254 + 0.5) |
| 292 |
elif unit == _UNIT_1M: |
| 293 |
return int(density * 0.0254 + 0.5) |
| 294 |
elif unit == _UNIT_10CM: |
| 295 |
return int(density * 0.254 + 0.5) |
| 296 |
elif unit == _UNIT_CM: |
| 297 |
return int(density * 2.54 + 0.5) |
| 298 |
elif unit == _UNIT_MM: |
| 299 |
return int(density * 25.4 + 0.5) |
| 300 |
elif unit == _UNIT_0_1MM: |
| 301 |
return density * 254 |
| 302 |
elif unit == _UNIT_0_01MM: |
| 303 |
return density * 2540 |
| 304 |
elif unit == _UNIT_UM: |
| 305 |
return density * 25400 |
| 306 |
return density |
| 307 |
|
| 308 |
|
| 309 |
def _convertToPx(value): |
| 310 |
matched = re.match(r"(\d+(?:\.\d+)?)?([a-z]*)$", value) |
| 311 |
if not matched: |
| 312 |
raise ValueError("unknown length value: %s" % value) |
| 313 |
|
| 314 |
length, unit = matched.groups() |
| 315 |
length = Decimal(length) |
| 316 |
if unit == "": |
| 317 |
return float(length) |
| 318 |
elif unit == "cm": |
| 319 |
return float(length * Decimal("96") / Decimal("2.54")) |
| 320 |
elif unit == "mm": |
| 321 |
return float(length * Decimal("96") / Decimal("25.4")) |
| 322 |
elif unit == "in": |
| 323 |
return float(length * Decimal("96")) |
| 324 |
elif unit == "pc": |
| 325 |
return float(length * Decimal("96") / Decimal("6")) |
| 326 |
elif unit == "pt": |
| 327 |
return float(length * Decimal("96") / Decimal("72")) |
| 328 |
elif unit == "px": |
| 329 |
return float(length) |
| 330 |
|
| 331 |
raise ValueError("unknown unit type: %s" % unit) |
| 332 |
|
| 333 |
|
| 334 |
def _read_orientation_from_exif_payload(exif_data): |
| 335 |
if len(exif_data) < 8: |
| 336 |
return -1 |
| 337 |
endian_token = exif_data[:2] |
| 338 |
if endian_token == b'II': |
| 339 |
endian = '<' |
| 340 |
elif endian_token == b'MM': |
| 341 |
endian = '>' |
| 342 |
else: |
| 343 |
return -1 |
| 344 |
|
| 345 |
try: |
| 346 |
first_ifd_offset = struct.unpack(endian + 'L', exif_data[4:8])[0] |
| 347 |
except struct.error: |
| 348 |
return -1 |
| 349 |
if first_ifd_offset + 2 > len(exif_data): |
| 350 |
return -1 |
| 351 |
|
| 352 |
try: |
| 353 |
ifd_count = struct.unpack(endian + 'H', exif_data[first_ifd_offset:first_ifd_offset + 2])[0] |
| 354 |
except struct.error: |
| 355 |
return -1 |
| 356 |
cursor = first_ifd_offset + 2 |
| 357 |
|
| 358 |
for _ in range(ifd_count): |
| 359 |
if cursor + 12 > len(exif_data): |
| 360 |
return -1 |
| 361 |
try: |
| 362 |
tag, datatype, count, value = struct.unpack(endian + 'HHLL', exif_data[cursor:cursor + 12]) |
| 363 |
except struct.error: |
| 364 |
return -1 |
| 365 |
if tag == 0x0112 and datatype == 3 and count == 1: |
| 366 |
return int(value / 65536) if endian == '>' else value & 0xFFFF |
| 367 |
cursor += 12 |
| 368 |
return -1 |
| 369 |
|
| 370 |
|
| 371 |
class _IsoFileBox(NamedTuple): |
| 372 |
offset: int |
| 373 |
size: int |
| 374 |
box_type: bytes |
| 375 |
header_size: int |
| 376 |
|
| 377 |
@property |
| 378 |
def payload_start(self): |
| 379 |
return self.offset + self.header_size |
| 380 |
|
| 381 |
@property |
| 382 |
def end(self): |
| 383 |
return self.offset + self.size |
| 384 |
|
| 385 |
|
| 386 |
class _ItemLocation(NamedTuple): |
| 387 |
construction_method: int |
| 388 |
data_reference_index: int |
| 389 |
base_offset: int |
| 390 |
extents: tuple |
| 391 |
|
| 392 |
|
| 393 |
def _read_exact(fhandle, size): |
| 394 |
data = fhandle.read(size) |
| 395 |
if len(data) != size: |
| 396 |
raise ValueError("Unexpected end of file") |
| 397 |
return data |
| 398 |
|
| 399 |
|
| 400 |
def _stream_size(fhandle): |
| 401 |
position = fhandle.seek(0, os.SEEK_CUR) |
| 402 |
size = fhandle.seek(0, os.SEEK_END) |
| 403 |
fhandle.seek(position) |
| 404 |
return size |
| 405 |
|
| 406 |
|
| 407 |
def _iter_iso_file_boxes(fhandle, start, end, head=None): |
| 408 |
offset = start |
| 409 |
while offset < end: |
| 410 |
if end - offset < 8: |
| 411 |
raise ValueError("Invalid ISO box header") |
| 412 |
if head is not None and offset + 8 <= len(head): |
| 413 |
size32, box_type = struct.unpack_from('>L4s', head, offset) |
| 414 |
else: |
| 415 |
cached = head[offset:] if head is not None and offset < len(head) else b'' |
| 416 |
fhandle.seek(offset + len(cached)) |
| 417 |
header = cached + _read_exact(fhandle, 8 - len(cached)) |
| 418 |
size32, box_type = struct.unpack('>L4s', header) |
| 419 |
header_size = 8 |
| 420 |
if size32 == 1: |
| 421 |
if head is not None and offset + 16 <= len(head): |
| 422 |
size = struct.unpack_from('>Q', head, offset + 8)[0] |
| 423 |
else: |
| 424 |
extended_offset = offset + 8 |
| 425 |
cached = (head[extended_offset:] if head is not None and |
| 426 |
extended_offset < len(head) else b'') |
| 427 |
fhandle.seek(extended_offset + len(cached)) |
| 428 |
extended = cached + _read_exact(fhandle, 8 - len(cached)) |
| 429 |
size = struct.unpack('>Q', extended)[0] |
| 430 |
header_size = 16 |
| 431 |
elif size32 == 0: |
| 432 |
size = end - offset |
| 433 |
else: |
| 434 |
size = size32 |
| 435 |
if size < header_size or offset + size > end: |
| 436 |
raise ValueError("Invalid ISO box size") |
| 437 |
yield _IsoFileBox(offset, size, box_type, header_size) |
| 438 |
offset += size |
| 439 |
|
| 440 |
|
| 441 |
def _read_box_prefix(fhandle, box, size, head=None): |
| 442 |
available = box.end - box.payload_start |
| 443 |
if available < size: |
| 444 |
raise ValueError("Invalid ISO box payload") |
| 445 |
if head is not None and box.payload_start + size <= len(head): |
| 446 |
return head[box.payload_start:box.payload_start + size] |
| 447 |
cached = (head[box.payload_start:] if head is not None and |
| 448 |
box.payload_start < len(head) else b'') |
| 449 |
fhandle.seek(box.payload_start + len(cached)) |
| 450 |
return cached + _read_exact(fhandle, size - len(cached)) |
| 451 |
|
| 452 |
|
| 453 |
def _parse_iinf(fhandle, box, item_types): |
| 454 |
header = _read_box_prefix(fhandle, box, min(8, box.end - box.payload_start)) |
| 455 |
if len(header) < 6: |
| 456 |
raise ValueError("Invalid iinf box") |
| 457 |
version = header[0] |
| 458 |
entries_start = box.payload_start + (6 if version == 0 else 8) |
| 459 |
if entries_start > box.end: |
| 460 |
raise ValueError("Invalid iinf box") |
| 461 |
for entry in _iter_iso_file_boxes(fhandle, entries_start, box.end): |
| 462 |
if entry.box_type != b'infe': |
| 463 |
continue |
| 464 |
prefix_size = min(16, entry.end - entry.payload_start) |
| 465 |
prefix = _read_box_prefix(fhandle, entry, prefix_size) |
| 466 |
if len(prefix) < 12: |
| 467 |
continue |
| 468 |
infe_version = prefix[0] |
| 469 |
if infe_version == 2: |
| 470 |
item_id = struct.unpack('>H', prefix[4:6])[0] |
| 471 |
item_type = prefix[8:12] |
| 472 |
elif infe_version >= 3 and len(prefix) >= 16: |
| 473 |
item_id = struct.unpack('>L', prefix[4:8])[0] |
| 474 |
item_type = prefix[12:16] |
| 475 |
else: |
| 476 |
continue |
| 477 |
item_types[item_id] = item_type |
| 478 |
|
| 479 |
|
| 480 |
def _parse_iloc(fhandle, box): |
| 481 |
payload_size = box.end - box.payload_start |
| 482 |
fhandle.seek(box.payload_start) |
| 483 |
data = _read_exact(fhandle, payload_size) |
| 484 |
if len(data) < 8: |
| 485 |
raise ValueError("Invalid iloc box") |
| 486 |
version = data[0] |
| 487 |
cursor = 4 |
| 488 |
offset_size = data[cursor] >> 4 |
| 489 |
length_size = data[cursor] & 0x0F |
| 490 |
cursor += 1 |
| 491 |
base_offset_size = data[cursor] >> 4 |
| 492 |
index_size = (data[cursor] & 0x0F) if version in (1, 2) else 0 |
| 493 |
cursor += 1 |
| 494 |
|
| 495 |
def take_int(size): |
| 496 |
nonlocal cursor |
| 497 |
if cursor + size > len(data): |
| 498 |
raise ValueError("Invalid iloc box") |
| 499 |
value = int.from_bytes(data[cursor:cursor + size], 'big') if size else 0 |
| 500 |
cursor += size |
| 501 |
return value |
| 502 |
|
| 503 |
item_count = take_int(2 if version < 2 else 4) |
| 504 |
locations = {} |
| 505 |
for _ in range(item_count): |
| 506 |
item_id = take_int(2 if version < 2 else 4) |
| 507 |
construction_method = take_int(2) & 0x0F if version in (1, 2) else 0 |
| 508 |
data_reference_index = take_int(2) |
| 509 |
base_offset = take_int(base_offset_size) |
| 510 |
extent_count = take_int(2) |
| 511 |
extents = [] |
| 512 |
for _ in range(extent_count): |
| 513 |
if version in (1, 2) and index_size: |
| 514 |
take_int(index_size) |
| 515 |
extent_offset = take_int(offset_size) |
| 516 |
extent_length = take_int(length_size) |
| 517 |
extents.append((extent_offset, extent_length)) |
| 518 |
locations[item_id] = _ItemLocation( |
| 519 |
construction_method, data_reference_index, base_offset, tuple(extents) |
| 520 |
) |
| 521 |
return locations |
| 522 |
|
| 523 |
|
| 524 |
def _parse_ipma(fhandle, box, associations): |
| 525 |
payload_size = box.end - box.payload_start |
| 526 |
fhandle.seek(box.payload_start) |
| 527 |
data = _read_exact(fhandle, payload_size) |
| 528 |
if len(data) < 8: |
| 529 |
raise ValueError("Invalid ipma box") |
| 530 |
version = data[0] |
| 531 |
flags = int.from_bytes(data[1:4], 'big') |
| 532 |
large_index = bool(flags & 1) |
| 533 |
cursor = 4 |
| 534 |
|
| 535 |
def take_int(size): |
| 536 |
nonlocal cursor |
| 537 |
if cursor + size > len(data): |
| 538 |
raise ValueError("Invalid ipma box") |
| 539 |
value = int.from_bytes(data[cursor:cursor + size], 'big') |
| 540 |
cursor += size |
| 541 |
return value |
| 542 |
|
| 543 |
entry_count = take_int(4) |
| 544 |
for _ in range(entry_count): |
| 545 |
item_id = take_int(2 if version == 0 else 4) |
| 546 |
association_count = take_int(1) |
| 547 |
indexes = [] |
| 548 |
for _ in range(association_count): |
| 549 |
value = take_int(2 if large_index else 1) |
| 550 |
indexes.append(value & (0x7FFF if large_index else 0x7F)) |
| 551 |
associations[item_id] = indexes |
| 552 |
|
| 553 |
|
| 554 |
def _parse_iprp(fhandle, box, properties, associations): |
| 555 |
for child in _iter_iso_file_boxes(fhandle, box.payload_start, box.end): |
| 556 |
if child.box_type == b'ipco': |
| 557 |
for prop in _iter_iso_file_boxes(fhandle, child.payload_start, child.end): |
| 558 |
value = None |
| 559 |
if prop.box_type == b'ispe': |
| 560 |
prefix = _read_box_prefix(fhandle, prop, 12) |
| 561 |
value = struct.unpack('>LL', prefix[4:12]) |
| 562 |
elif prop.box_type == b'irot': |
| 563 |
prefix = _read_box_prefix(fhandle, prop, 5) |
| 564 |
value = _HEIF_IROT_TO_EXIF.get(prefix[4] & 0x03, -1) |
| 565 |
properties.append((prop.box_type, value)) |
| 566 |
elif child.box_type == b'ipma': |
| 567 |
_parse_ipma(fhandle, child, associations) |
| 568 |
|
| 569 |
|
| 570 |
class _ExtentReader: |
| 571 |
def __init__(self, fhandle, extents): |
| 572 |
self._fhandle = fhandle |
| 573 |
self._extents = [] |
| 574 |
logical_start = 0 |
| 575 |
for file_offset, length in extents: |
| 576 |
if length <= 0: |
| 577 |
continue |
| 578 |
self._extents.append((logical_start, logical_start + length, file_offset)) |
| 579 |
logical_start += length |
| 580 |
self._size = logical_start |
| 581 |
self._position = 0 |
| 582 |
|
| 583 |
def seek(self, offset, whence=0): |
| 584 |
if whence == os.SEEK_SET: |
| 585 |
position = offset |
| 586 |
elif whence == os.SEEK_CUR: |
| 587 |
position = self._position + offset |
| 588 |
elif whence == os.SEEK_END: |
| 589 |
position = self._size + offset |
| 590 |
else: |
| 591 |
raise ValueError("invalid whence") |
| 592 |
if position < 0: |
| 593 |
raise ValueError("negative seek position") |
| 594 |
self._position = position |
| 595 |
return position |
| 596 |
|
| 597 |
def read(self, size=-1): |
| 598 |
if size < 0: |
| 599 |
size = self._size - self._position |
| 600 |
size = min(size, max(0, self._size - self._position)) |
| 601 |
chunks = [] |
| 602 |
remaining = size |
| 603 |
while remaining: |
| 604 |
for logical_start, logical_end, file_offset in self._extents: |
| 605 |
if logical_start <= self._position < logical_end: |
| 606 |
available = min(remaining, logical_end - self._position) |
| 607 |
self._fhandle.seek(file_offset + self._position - logical_start) |
| 608 |
chunk = self._fhandle.read(available) |
| 609 |
if not chunk: |
| 610 |
return b"".join(chunks) |
| 611 |
chunks.append(chunk) |
| 612 |
self._position += len(chunk) |
| 613 |
remaining -= len(chunk) |
| 614 |
break |
| 615 |
else: |
| 616 |
break |
| 617 |
return b"".join(chunks) |
| 618 |
|
| 619 |
|
| 620 |
def _read_tiff_orientation_stream(fhandle, base_offset=0): |
| 621 |
fhandle.seek(base_offset) |
| 622 |
header = fhandle.read(8) |
| 623 |
if len(header) < 8: |
| 624 |
return -1 |
| 625 |
if header[:2] == b'II': |
| 626 |
endian = '<' |
| 627 |
elif header[:2] == b'MM': |
| 628 |
endian = '>' |
| 629 |
else: |
| 630 |
return -1 |
| 631 |
try: |
| 632 |
if struct.unpack(endian + 'H', header[2:4])[0] != 42: |
| 633 |
return -1 |
| 634 |
ifd_offset = struct.unpack(endian + 'L', header[4:8])[0] |
| 635 |
fhandle.seek(base_offset + ifd_offset) |
| 636 |
count = struct.unpack(endian + 'H', _read_exact(fhandle, 2))[0] |
| 637 |
for _ in range(count): |
| 638 |
entry = _read_exact(fhandle, 12) |
| 639 |
tag, datatype, value_count = struct.unpack(endian + 'HHI', entry[:8]) |
| 640 |
if tag == 0x0112 and datatype == 3 and value_count == 1: |
| 641 |
return struct.unpack(endian + 'H', entry[8:10])[0] |
| 642 |
except (struct.error, ValueError): |
| 643 |
return -1 |
| 644 |
return -1 |
| 645 |
|
| 646 |
|
| 647 |
def _read_heif_metadata_stream(fhandle, *, read_rotation=True, head=None): |
| 648 |
"""Read HEIF metadata after locating ftyp and meta in one top-level scan.""" |
| 649 |
file_size = _stream_size(fhandle) |
| 650 |
is_heif = False |
| 651 |
meta_box = None |
| 652 |
for box in _iter_iso_file_boxes(fhandle, 0, file_size, head=head): |
| 653 |
if box.box_type == b'ftyp': |
| 654 |
if box.end - box.payload_start < 8: |
| 655 |
return -1, -1, -1, -1 |
| 656 |
prefix = _read_box_prefix(fhandle, box, 8, head=head) |
| 657 |
major_brand = prefix[:4] |
| 658 |
is_heif = major_brand in _HEIF_BRANDS |
| 659 |
brand_offset = box.payload_start + 8 |
| 660 |
while not is_heif and brand_offset + 4 <= box.end: |
| 661 |
if head is not None and brand_offset + 4 <= len(head): |
| 662 |
brand = head[brand_offset:brand_offset + 4] |
| 663 |
else: |
| 664 |
fhandle.seek(brand_offset) |
| 665 |
brand = _read_exact(fhandle, 4) |
| 666 |
is_heif = brand in _HEIF_BRANDS |
| 667 |
brand_offset += 4 |
| 668 |
elif box.box_type == b'meta': |
| 669 |
meta_box = box |
| 670 |
if is_heif and meta_box is not None: |
| 671 |
break |
| 672 |
if not is_heif or meta_box is None or meta_box.end - meta_box.payload_start < 4: |
| 673 |
return -1, -1, -1, -1 |
| 674 |
|
| 675 |
primary_item_id = None |
| 676 |
properties = [] |
| 677 |
associations = {} |
| 678 |
item_types = {} |
| 679 |
item_locations = {} |
| 680 |
idat_payload_start = None |
| 681 |
children_start = meta_box.payload_start + 4 |
| 682 |
for box in _iter_iso_file_boxes(fhandle, children_start, meta_box.end, head=head): |
| 683 |
if box.box_type == b'pitm': |
| 684 |
prefix = _read_box_prefix(fhandle, box, min(8, box.end - box.payload_start)) |
| 685 |
if len(prefix) >= 6: |
| 686 |
item_id_data = prefix[4:6] if prefix[0] == 0 else prefix[4:8] |
| 687 |
primary_item_id = int.from_bytes(item_id_data, 'big') |
| 688 |
elif box.box_type == b'iinf' and read_rotation: |
| 689 |
_parse_iinf(fhandle, box, item_types) |
| 690 |
elif box.box_type == b'iloc' and read_rotation: |
| 691 |
item_locations.update(_parse_iloc(fhandle, box)) |
| 692 |
elif box.box_type == b'iprp': |
| 693 |
_parse_iprp(fhandle, box, properties, associations) |
| 694 |
elif box.box_type == b'idat' and read_rotation: |
| 695 |
idat_payload_start = box.payload_start |
| 696 |
|
| 697 |
target_indexes = associations.get(primary_item_id, list(range(1, len(properties) + 1))) |
| 698 |
width = height = property_rotation = exif_rotation = -1 |
| 699 |
for index in target_indexes: |
| 700 |
if not 1 <= index <= len(properties): |
| 701 |
continue |
| 702 |
property_type, value = properties[index - 1] |
| 703 |
if property_type == b'ispe' and value is not None: |
| 704 |
width, height = value |
| 705 |
elif read_rotation and property_type == b'irot' and value is not None: |
| 706 |
property_rotation = value |
| 707 |
|
| 708 |
for item_id, item_type in item_types.items() if property_rotation == -1 else (): |
| 709 |
if item_type != b'Exif': |
| 710 |
continue |
| 711 |
location = item_locations.get(item_id) |
| 712 |
if location is None or location.data_reference_index != 0: |
| 713 |
continue |
| 714 |
if location.construction_method == 0: |
| 715 |
origin = location.base_offset |
| 716 |
elif location.construction_method == 1 and idat_payload_start is not None: |
| 717 |
origin = idat_payload_start + location.base_offset |
| 718 |
else: |
| 719 |
continue |
| 720 |
extents = [(origin + offset, length) for offset, length in location.extents] |
| 721 |
reader = _ExtentReader(fhandle, extents) |
| 722 |
offset_data = reader.read(4) |
| 723 |
if len(offset_data) != 4: |
| 724 |
continue |
| 725 |
tiff_offset = 4 + struct.unpack('>L', offset_data)[0] |
| 726 |
exif_rotation = _read_tiff_orientation_stream(reader, tiff_offset) |
| 727 |
if exif_rotation != -1: |
| 728 |
break |
| 729 |
|
| 730 |
return width, height, property_rotation, exif_rotation |
| 731 |
|
| 732 |
|
| 733 |
def _is_rotation_swapped(rotation): |
| 734 |
return rotation in {5, 6, 7, 8} |
| 735 |
|
| 736 |
|
| 737 |
def _detect_image_format(head): |
| 738 |
if len(head) >= 10 and head[:6] in (b'GIF87a', b'GIF89a'): |
| 739 |
return 'gif' |
| 740 |
if len(head) >= 8 and head.startswith(b'\211PNG\r\n\032\n'): |
| 741 |
return 'png' |
| 742 |
if len(head) >= 2 and head.startswith(b'\377\330'): |
| 743 |
return 'jpeg' |
| 744 |
if len(head) >= 12 and head.startswith(b'\x00\x00\x00\x0cjP \r\n\x87\n'): |
| 745 |
return 'jp2' |
| 746 |
if len(head) >= 8 and head[4:8] == b'ftyp': |
| 747 |
return 'iso' |
| 748 |
if len(head) >= 8 and head[:4] in (b'MM\x00*', b'II*\x00', b'II+\x00'): |
| 749 |
return 'tiff' |
| 750 |
if len(head) >= 5 and (head.startswith(b'<?xml') or head.startswith(b'<svg')): |
| 751 |
return 'svg' |
| 752 |
if head[:1] == b'P' and head[1:2] in b'123456': |
| 753 |
return 'netpbm' |
| 754 |
if len(head) >= 16 and head.startswith(b'RIFF') and head[8:12] == b'WEBP': |
| 755 |
return 'webp' |
| 756 |
if head.startswith(b'BM'): |
| 757 |
return 'bmp' |
| 758 |
return 'unknown' |
| 759 |
|
| 760 |
|
| 761 |
def _read_png_dpi(fhandle, head=None): |
| 762 |
offset = 8 |
| 763 |
while True: |
| 764 |
if head is not None and offset + 8 <= len(head): |
| 765 |
header = head[offset:offset + 8] |
| 766 |
else: |
| 767 |
fhandle.seek(offset) |
| 768 |
header = fhandle.read(8) |
| 769 |
if len(header) != 8: |
| 770 |
raise ValueError("Invalid PNG file") |
| 771 |
length, chunk_type = struct.unpack('>L4s', header) |
| 772 |
if chunk_type == b'pHYs': |
| 773 |
if length < 9: |
| 774 |
raise ValueError("Invalid PNG file") |
| 775 |
payload_start = offset + 8 |
| 776 |
if head is not None and payload_start + 9 <= len(head): |
| 777 |
payload = head[payload_start:payload_start + 9] |
| 778 |
else: |
| 779 |
fhandle.seek(payload_start) |
| 780 |
payload = _read_exact(fhandle, 9) |
| 781 |
xdensity, ydensity, unit = struct.unpack('>LLB', payload) |
| 782 |
if unit: |
| 783 |
return (_convertToDPI(xdensity, _UNIT_1M), |
| 784 |
_convertToDPI(ydensity, _UNIT_1M)) |
| 785 |
return xdensity, ydensity |
| 786 |
if chunk_type in (b'IDAT', b'IEND'): |
| 787 |
return -1, -1 |
| 788 |
offset += 12 + length |
| 789 |
|
| 790 |
|
| 791 |
def _read_jpeg_metadata(fhandle, *, size, dpi, rotation, channels, head=None): |
| 792 |
width = height = xdpi = ydpi = orientation = channel_count = -1 |
| 793 |
found_sof = False |
| 794 |
found_dpi = False |
| 795 |
found_rotation = False |
| 796 |
position = 2 |
| 797 |
|
| 798 |
def done(): |
| 799 |
needed_sof = not (size or channels) or found_sof |
| 800 |
needed_dpi = not dpi or found_dpi |
| 801 |
needed_rotation = not rotation or found_rotation |
| 802 |
return needed_sof and needed_dpi and needed_rotation |
| 803 |
|
| 804 |
# Parse markers already present in the format-detection buffer directly. |
| 805 |
# If a segment crosses the boundary, combine the cached prefix with only |
| 806 |
# the unread suffix and then continue on the original stream. |
| 807 |
while head is not None and position < len(head): |
| 808 |
marker_start = head.find(b'\xff', position) |
| 809 |
if marker_start == -1: |
| 810 |
position = len(head) |
| 811 |
break |
| 812 |
marker_cursor = marker_start + 1 |
| 813 |
while marker_cursor < len(head) and head[marker_cursor] == 0xff: |
| 814 |
marker_cursor += 1 |
| 815 |
if marker_cursor >= len(head): |
| 816 |
position = marker_start |
| 817 |
break |
| 818 |
marker = head[marker_cursor] |
| 819 |
position = marker_cursor + 1 |
| 820 |
if marker in (0xd9, 0xda): |
| 821 |
position = -1 |
| 822 |
break |
| 823 |
if marker == 0x01 or 0xd0 <= marker <= 0xd7: |
| 824 |
continue |
| 825 |
if position + 2 > len(head): |
| 826 |
position = marker_start |
| 827 |
break |
| 828 |
segment_size = struct.unpack_from('>H', head, position)[0] |
| 829 |
if segment_size < 2: |
| 830 |
raise ValueError("Invalid JPEG segment size") |
| 831 |
payload_size = segment_size - 2 |
| 832 |
payload_start = position + 2 |
| 833 |
payload_end = payload_start + payload_size |
| 834 |
|
| 835 |
read_size = 0 |
| 836 |
if marker == 0xe0 and dpi: |
| 837 |
read_size = min(payload_size, 14) |
| 838 |
elif marker == 0xe1 and rotation: |
| 839 |
read_size = payload_size |
| 840 |
elif 0xc0 <= marker <= 0xcf and marker not in _JPEG_NO_SOF_MARKERS: |
| 841 |
read_size = min(payload_size, 6) |
| 842 |
|
| 843 |
payload = b'' |
| 844 |
if read_size: |
| 845 |
cached_end = min(payload_start + read_size, len(head)) |
| 846 |
payload = head[payload_start:cached_end] |
| 847 |
remaining = read_size - len(payload) |
| 848 |
if remaining: |
| 849 |
fhandle.seek(cached_end) |
| 850 |
payload += fhandle.read(remaining) |
| 851 |
|
| 852 |
if marker == 0xe0 and dpi: |
| 853 |
if len(payload) >= 12 and payload.startswith(b'JFIF\x00'): |
| 854 |
unit, xdensity, ydensity = struct.unpack('>BHH', payload[7:12]) |
| 855 |
if unit in (0, 1): |
| 856 |
xdpi, ydpi = xdensity, ydensity |
| 857 |
elif unit == 2: |
| 858 |
xdpi = _convertToDPI(xdensity, _UNIT_CM) |
| 859 |
ydpi = _convertToDPI(ydensity, _UNIT_CM) |
| 860 |
found_dpi = True |
| 861 |
elif marker == 0xe1 and rotation: |
| 862 |
if payload.startswith(b'Exif\x00\x00'): |
| 863 |
orientation = _read_orientation_from_exif_payload(payload[6:]) |
| 864 |
found_rotation = orientation != -1 |
| 865 |
elif 0xc0 <= marker <= 0xcf and marker not in _JPEG_NO_SOF_MARKERS: |
| 866 |
if len(payload) < 6: |
| 867 |
raise ValueError("Invalid JPEG file") |
| 868 |
height, width, channel_count = struct.unpack('>xHHB', payload[:6]) |
| 869 |
found_sof = True |
| 870 |
|
| 871 |
position = payload_end |
| 872 |
if done(): |
| 873 |
break |
| 874 |
|
| 875 |
if not done() and position >= 0: |
| 876 |
fhandle.seek(position) |
| 877 |
while True: |
| 878 |
if done() or position < 0: |
| 879 |
break |
| 880 |
marker_start = fhandle.read(1) |
| 881 |
while marker_start and marker_start != b'\xff': |
| 882 |
marker_start = fhandle.read(1) |
| 883 |
if not marker_start: |
| 884 |
break |
| 885 |
marker_byte = fhandle.read(1) |
| 886 |
while marker_byte == b'\xff': |
| 887 |
marker_byte = fhandle.read(1) |
| 888 |
if not marker_byte: |
| 889 |
break |
| 890 |
marker = marker_byte[0] |
| 891 |
if marker in (0xd9, 0xda): |
| 892 |
break |
| 893 |
if marker == 0x01 or 0xd0 <= marker <= 0xd7: |
| 894 |
continue |
| 895 |
try: |
| 896 |
segment_size = struct.unpack('>H', _read_exact(fhandle, 2))[0] |
| 897 |
except (struct.error, ValueError): |
| 898 |
raise ValueError("Invalid JPEG file") |
| 899 |
if segment_size < 2: |
| 900 |
raise ValueError("Invalid JPEG segment size") |
| 901 |
payload_size = segment_size - 2 |
| 902 |
payload_start = fhandle.seek(0, os.SEEK_CUR) |
| 903 |
|
| 904 |
if marker == 0xe0 and dpi: |
| 905 |
payload = fhandle.read(min(payload_size, 14)) |
| 906 |
if len(payload) >= 12 and payload.startswith(b'JFIF\x00'): |
| 907 |
unit, xdensity, ydensity = struct.unpack('>BHH', payload[7:12]) |
| 908 |
if unit in (0, 1): |
| 909 |
xdpi, ydpi = xdensity, ydensity |
| 910 |
elif unit == 2: |
| 911 |
xdpi = _convertToDPI(xdensity, _UNIT_CM) |
| 912 |
ydpi = _convertToDPI(ydensity, _UNIT_CM) |
| 913 |
found_dpi = True |
| 914 |
elif marker == 0xe1 and rotation: |
| 915 |
payload = fhandle.read(payload_size) |
| 916 |
if payload.startswith(b'Exif\x00\x00'): |
| 917 |
orientation = _read_orientation_from_exif_payload(payload[6:]) |
| 918 |
found_rotation = orientation != -1 |
| 919 |
elif 0xc0 <= marker <= 0xcf and marker not in _JPEG_NO_SOF_MARKERS: |
| 920 |
payload = fhandle.read(min(payload_size, 6)) |
| 921 |
if len(payload) < 6: |
| 922 |
raise ValueError("Invalid JPEG file") |
| 923 |
height, width, channel_count = struct.unpack('>xHHB', payload[:6]) |
| 924 |
found_sof = True |
| 925 |
|
| 926 |
fhandle.seek(payload_start + payload_size) |
| 927 |
if done(): |
| 928 |
break |
| 929 |
|
| 930 |
if (size or channels) and not found_sof: |
| 931 |
raise ValueError("Invalid JPEG file") |
| 932 |
return _ImageMetadata( |
| 933 |
width if size else -1, |
| 934 |
height if size else -1, |
| 935 |
orientation if rotation else -1, |
| 936 |
xdpi if dpi else -1, |
| 937 |
ydpi if dpi else -1, |
| 938 |
-1, |
| 939 |
channel_count if channels else -1, |
| 940 |
) |
| 941 |
|
| 942 |
|
| 943 |
def _inline_tiff_value(entry, endian, datatype): |
| 944 |
if datatype == 3: |
| 945 |
return struct.unpack(endian + 'H', entry[:2])[0] |
| 946 |
if datatype == 4: |
| 947 |
return struct.unpack(endian + 'L', entry[:4])[0] |
| 948 |
return None |
| 949 |
|
| 950 |
|
| 951 |
def _read_tiff_metadata(fhandle, *, size, rotation, head=None): |
| 952 |
if head is not None and len(head) >= 16: |
| 953 |
header = head[:16] |
| 954 |
else: |
| 955 |
fhandle.seek(0) |
| 956 |
header = _read_exact(fhandle, 16) |
| 957 |
if header.startswith(b'MM\x00*'): |
| 958 |
endian, bigtiff = '>', False |
| 959 |
elif header.startswith(b'II*\x00'): |
| 960 |
endian, bigtiff = '<', False |
| 961 |
elif header.startswith(b'II+\x00'): |
| 962 |
endian, bigtiff = '<', True |
| 963 |
else: |
| 964 |
raise ValueError("Invalid TIFF file") |
| 965 |
|
| 966 |
if bigtiff: |
| 967 |
if struct.unpack(endian + 'H', header[4:6])[0] != 8: |
| 968 |
raise ValueError("Invalid BigTIFF file") |
| 969 |
ifd_offset = struct.unpack(endian + 'Q', header[8:16])[0] |
| 970 |
count_size = 8 |
| 971 |
entry_size = 20 |
| 972 |
else: |
| 973 |
ifd_offset = struct.unpack(endian + 'L', header[4:8])[0] |
| 974 |
count_size = 2 |
| 975 |
entry_size = 12 |
| 976 |
|
| 977 |
if head is not None and ifd_offset + count_size <= len(head): |
| 978 |
count_data = head[ifd_offset:ifd_offset + count_size] |
| 979 |
else: |
| 980 |
fhandle.seek(ifd_offset) |
| 981 |
count_data = _read_exact(fhandle, count_size) |
| 982 |
entry_count = struct.unpack(endian + ('Q' if bigtiff else 'H'), count_data)[0] |
| 983 |
entry_offset = ifd_offset + count_size |
| 984 |
|
| 985 |
width = height = orientation = -1 |
| 986 |
for _ in range(entry_count): |
| 987 |
if head is not None and entry_offset + entry_size <= len(head): |
| 988 |
entry = head[entry_offset:entry_offset + entry_size] |
| 989 |
else: |
| 990 |
fhandle.seek(entry_offset) |
| 991 |
entry = _read_exact(fhandle, entry_size) |
| 992 |
entry_offset += entry_size |
| 993 |
tag, datatype = struct.unpack(endian + 'HH', entry[:4]) |
| 994 |
value_field = entry[12:20] if bigtiff else entry[8:12] |
| 995 |
if tag == 256 and size: |
| 996 |
value = _inline_tiff_value(value_field, endian, datatype) |
| 997 |
if value is not None: |
| 998 |
width = value |
| 999 |
elif tag == 257 and size: |
| 1000 |
value = _inline_tiff_value(value_field, endian, datatype) |
| 1001 |
if value is not None: |
| 1002 |
height = value |
| 1003 |
elif tag == 274 and rotation: |
| 1004 |
value = _inline_tiff_value(value_field, endian, datatype) |
| 1005 |
if value is not None: |
| 1006 |
orientation = value |
| 1007 |
size_done = not size or (width != -1 and height != -1) |
| 1008 |
rotation_done = not rotation or orientation != -1 |
| 1009 |
if size_done and rotation_done: |
| 1010 |
break |
| 1011 |
if size and (width == -1 or height == -1): |
| 1012 |
raise ValueError("Invalid TIFF file: missing dimensions") |
| 1013 |
return _ImageMetadata(width, height, orientation) |
| 1014 |
|
| 1015 |
|
| 1016 |
def _iter_jp2_boxes(fhandle, start, container_size=None, head=None): |
| 1017 |
remaining = container_size |
| 1018 |
box_start = start |
| 1019 |
while remaining is None or remaining > 0: |
| 1020 |
if remaining is not None and remaining < 8: |
| 1021 |
raise ValueError("Invalid JPEG2000 box size") |
| 1022 |
if head is not None and box_start + 8 <= len(head): |
| 1023 |
header = head[box_start:box_start + 8] |
| 1024 |
else: |
| 1025 |
cached = (head[box_start:] if head is not None and |
| 1026 |
box_start < len(head) else b'') |
| 1027 |
fhandle.seek(box_start + len(cached)) |
| 1028 |
header = cached + fhandle.read(8 - len(cached)) |
| 1029 |
if not header and remaining is None: |
| 1030 |
return |
| 1031 |
if len(header) != 8: |
| 1032 |
raise ValueError("Invalid JPEG2000 box header") |
| 1033 |
box_size, box_type = struct.unpack('>L4s', header) |
| 1034 |
header_size = 8 |
| 1035 |
if box_size == 1: |
| 1036 |
if head is not None and box_start + 16 <= len(head): |
| 1037 |
box_size = struct.unpack_from('>Q', head, box_start + 8)[0] |
| 1038 |
else: |
| 1039 |
extended_offset = box_start + 8 |
| 1040 |
cached = (head[extended_offset:] if head is not None and |
| 1041 |
extended_offset < len(head) else b'') |
| 1042 |
fhandle.seek(extended_offset + len(cached)) |
| 1043 |
extended = cached + _read_exact(fhandle, 8 - len(cached)) |
| 1044 |
box_size = struct.unpack('>Q', extended)[0] |
| 1045 |
header_size = 16 |
| 1046 |
elif box_size == 0: |
| 1047 |
box_size = remaining |
| 1048 |
if box_size is None: |
| 1049 |
payload_size = _stream_size(fhandle) - box_start - header_size |
| 1050 |
else: |
| 1051 |
if box_size < header_size or (remaining is not None and box_size > remaining): |
| 1052 |
raise ValueError("Invalid JPEG2000 box size") |
| 1053 |
payload_size = box_size - header_size |
| 1054 |
payload_start = box_start + header_size |
| 1055 |
yield box_type, payload_start, payload_size |
| 1056 |
box_start = payload_start + payload_size |
| 1057 |
if remaining is not None: |
| 1058 |
remaining -= box_size |
| 1059 |
|
| 1060 |
|
| 1061 |
def _read_jp2_metadata(fhandle, *, size, dpi, head=None): |
| 1062 |
jp2_header = None |
| 1063 |
for box_type, payload_start, payload_size in _iter_jp2_boxes(fhandle, 0, head=head): |
| 1064 |
if box_type == b'jp2h': |
| 1065 |
jp2_header = (payload_start, payload_size) |
| 1066 |
break |
| 1067 |
if jp2_header is None: |
| 1068 |
raise ValueError("Invalid JPEG2000 file") |
| 1069 |
|
| 1070 |
width = height = xdpi = ydpi = -1 |
| 1071 |
for box_type, payload_start, payload_size in _iter_jp2_boxes( |
| 1072 |
fhandle, jp2_header[0], jp2_header[1], head=head): |
| 1073 |
if box_type == b'ihdr' and size: |
| 1074 |
if head is not None and payload_start + 8 <= len(head): |
| 1075 |
dimensions = head[payload_start:payload_start + 8] |
| 1076 |
else: |
| 1077 |
cached = (head[payload_start:] if head is not None and |
| 1078 |
payload_start < len(head) else b'') |
| 1079 |
fhandle.seek(payload_start + len(cached)) |
| 1080 |
dimensions = cached + _read_exact(fhandle, 8 - len(cached)) |
| 1081 |
height, width = struct.unpack('>LL', dimensions) |
| 1082 |
elif box_type == b'res ' and dpi: |
| 1083 |
for resolution_type, resolution_start, resolution_size in _iter_jp2_boxes( |
| 1084 |
fhandle, payload_start, payload_size, head=head): |
| 1085 |
if resolution_type != b'resd': |
| 1086 |
continue |
| 1087 |
if resolution_size < 10: |
| 1088 |
raise ValueError("Invalid JPEG2000 resolution box") |
| 1089 |
if head is not None and resolution_start + 10 <= len(head): |
| 1090 |
resolution = head[resolution_start:resolution_start + 10] |
| 1091 |
else: |
| 1092 |
cached = b'' |
| 1093 |
if head is not None and resolution_start < len(head): |
| 1094 |
cached = head[resolution_start:] |
| 1095 |
fhandle.seek(resolution_start + len(cached)) |
| 1096 |
resolution = cached + _read_exact(fhandle, 10 - len(cached)) |
| 1097 |
(y_numerator, y_denominator, x_numerator, x_denominator, |
| 1098 |
y_exponent, x_exponent) = struct.unpack('>HHHHbb', resolution) |
| 1099 |
if x_denominator and y_denominator: |
| 1100 |
x_density = x_numerator / x_denominator * (10 ** x_exponent) |
| 1101 |
y_density = y_numerator / y_denominator * (10 ** y_exponent) |
| 1102 |
xdpi = _convertToDPI(x_density, _UNIT_1M) |
| 1103 |
ydpi = _convertToDPI(y_density, _UNIT_1M) |
| 1104 |
break |
| 1105 |
if (not size or width != -1) and (not dpi or xdpi != -1): |
| 1106 |
break |
| 1107 |
if size and (width == -1 or height == -1): |
| 1108 |
raise ValueError("Invalid JPEG2000 image header box") |
| 1109 |
return _ImageMetadata(width, height, -1, xdpi, ydpi) |
| 1110 |
|
| 1111 |
|
| 1112 |
def _read_svg_size(fhandle, head=None): |
| 1113 |
try: |
| 1114 |
prefix = head or b'' |
| 1115 |
if len(prefix) < 1024: |
| 1116 |
fhandle.seek(len(prefix)) |
| 1117 |
prefix += fhandle.read(1024 - len(prefix)) |
| 1118 |
data = prefix.decode('utf-8') |
| 1119 |
width = re.search(r'''[^-]width=(["'])(.*?)\1''', data).group(2) |
| 1120 |
height = re.search(r'''[^-]height=(["'])(.*?)\1''', data).group(2) |
| 1121 |
except Exception: |
| 1122 |
raise ValueError("Invalid SVG file") |
| 1123 |
return _convertToPx(width), _convertToPx(height) |
| 1124 |
|
| 1125 |
|
| 1126 |
def _read_netpbm_size(fhandle, head=None): |
| 1127 |
data = bytearray(head or b'') |
| 1128 |
cursor = 2 |
| 1129 |
|
| 1130 |
def ensure_data(): |
| 1131 |
if cursor < len(data): |
| 1132 |
return True |
| 1133 |
fhandle.seek(len(data)) |
| 1134 |
chunk = fhandle.read(64) |
| 1135 |
if not chunk: |
| 1136 |
return False |
| 1137 |
data.extend(chunk) |
| 1138 |
return True |
| 1139 |
|
| 1140 |
values = [] |
| 1141 |
while len(values) < 2: |
| 1142 |
if not ensure_data(): |
| 1143 |
raise ValueError("Invalid Netpbm file") |
| 1144 |
value = bytes([data[cursor]]) |
| 1145 |
cursor += 1 |
| 1146 |
if value.isspace(): |
| 1147 |
continue |
| 1148 |
if value == b'#': |
| 1149 |
while True: |
| 1150 |
if not ensure_data(): |
| 1151 |
raise ValueError("Invalid Netpbm file") |
| 1152 |
value = bytes([data[cursor]]) |
| 1153 |
cursor += 1 |
| 1154 |
if value == b'\n': |
| 1155 |
break |
| 1156 |
continue |
| 1157 |
if not value.isdigit(): |
| 1158 |
raise ValueError("Invalid character found in Netpbm file") |
| 1159 |
digits = value |
| 1160 |
while ensure_data(): |
| 1161 |
value = bytes([data[cursor]]) |
| 1162 |
cursor += 1 |
| 1163 |
if not value.isdigit(): |
| 1164 |
break |
| 1165 |
digits += value |
| 1166 |
values.append(int(digits)) |
| 1167 |
if value.isdigit() and len(values) < 2: |
| 1168 |
raise ValueError("Invalid Netpbm file") |
| 1169 |
return tuple(values) |
| 1170 |
|
| 1171 |
|
| 1172 |
def _read_image_metadata(fhandle, *, size=True, dpi=True, colors=True, |
| 1173 |
rotation=True, channels=True): |
| 1174 |
if not any((size, dpi, colors, rotation, channels)): |
| 1175 |
return _ImageMetadata() |
| 1176 |
fhandle.seek(0) |
| 1177 |
head = fhandle.read(64) |
| 1178 |
image_format = _detect_image_format(head) |
| 1179 |
|
| 1180 |
if image_format == 'jpeg': |
| 1181 |
if not any((size, dpi, rotation, channels)): |
| 1182 |
return _ImageMetadata() |
| 1183 |
return _read_jpeg_metadata( |
| 1184 |
fhandle, size=size, dpi=dpi, rotation=rotation, channels=channels, head=head |
| 1185 |
) |
| 1186 |
if image_format == 'tiff': |
| 1187 |
if not (size or rotation): |
| 1188 |
return _ImageMetadata() |
| 1189 |
return _read_tiff_metadata(fhandle, size=size, rotation=rotation, head=head) |
| 1190 |
if image_format == 'jp2': |
| 1191 |
if not (size or dpi): |
| 1192 |
return _ImageMetadata() |
| 1193 |
return _read_jp2_metadata(fhandle, size=size, dpi=dpi, head=head) |
| 1194 |
if image_format == 'iso': |
| 1195 |
if not (size or rotation): |
| 1196 |
return _ImageMetadata() |
| 1197 |
width, height, property_rotation, exif_rotation = _read_heif_metadata_stream( |
| 1198 |
fhandle, read_rotation=rotation, head=head |
| 1199 |
) |
| 1200 |
orientation = property_rotation if property_rotation != -1 else exif_rotation |
| 1201 |
return _ImageMetadata( |
| 1202 |
width if size else -1, |
| 1203 |
height if size else -1, |
| 1204 |
orientation if rotation else -1, |
| 1205 |
) |
| 1206 |
if image_format == 'png': |
| 1207 |
if len(head) < 26 or head[12:16] != b'IHDR': |
| 1208 |
raise ValueError("Invalid PNG file") |
| 1209 |
width, height = struct.unpack('>LL', head[16:24]) if size else (-1, -1) |
| 1210 |
bit_depth, color_type = head[24], head[25] |
| 1211 |
color_channels = {0: 1, 2: 3, 3: 1, 4: 1, 6: 3}.get(color_type) |
| 1212 |
color_count = 2 ** (bit_depth * color_channels) if colors and color_channels else -1 |
| 1213 |
channel_count = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}.get(color_type, -1) if channels else -1 |
| 1214 |
xdpi, ydpi = _read_png_dpi(fhandle, head=head) if dpi else (-1, -1) |
| 1215 |
return _ImageMetadata(width, height, -1, xdpi, ydpi, color_count, channel_count) |
| 1216 |
if image_format == 'gif': |
| 1217 |
width, height = struct.unpack('<hh', head[6:10]) if size else (-1, -1) |
| 1218 |
color_count = -1 |
| 1219 |
if colors and len(head) >= 11 and head[10] & 0x80: |
| 1220 |
color_count = 2 ** ((head[10] & 0x07) + 1) |
| 1221 |
return _ImageMetadata(width, height, -1, -1, -1, color_count, 3 if channels else -1) |
| 1222 |
if image_format == 'bmp': |
| 1223 |
width, height = struct.unpack('<ll', head[18:26]) if size else (-1, -1) |
| 1224 |
height = abs(height) if size else -1 |
| 1225 |
channel_count = -1 |
| 1226 |
if channels and len(head) >= 30: |
| 1227 |
depth = struct.unpack('<H', head[28:30])[0] |
| 1228 |
channel_count = 1 if depth <= 8 else 3 if depth == 24 else 4 if depth == 32 else -1 |
| 1229 |
return _ImageMetadata(width, height, channels=channel_count) |
| 1230 |
if image_format == 'svg': |
| 1231 |
width, height = _read_svg_size(fhandle, head=head) if size else (-1, -1) |
| 1232 |
return _ImageMetadata(width, height) |
| 1233 |
if image_format == 'netpbm': |
| 1234 |
width, height = _read_netpbm_size(fhandle, head=head) if size else (-1, -1) |
| 1235 |
return _ImageMetadata(width, height) |
| 1236 |
if image_format == 'webp': |
| 1237 |
width = height = -1 |
| 1238 |
if size and head[12:16] == b'VP8 ': |
| 1239 |
width, height = struct.unpack('<HH', head[26:30]) |
| 1240 |
elif size and head[12:16] == b'VP8X': |
| 1241 |
width = struct.unpack('<I', head[24:27] + b'\0')[0] + 1 |
| 1242 |
height = struct.unpack('<I', head[27:30] + b'\0')[0] + 1 |
| 1243 |
elif size and head[12:16] == b'VP8L': |
| 1244 |
value = head[21:25] |
| 1245 |
width = (((value[1] & 63) << 8) | value[0]) + 1 |
| 1246 |
height = (((value[3] & 15) << 10) | (value[2] << 2) | ((value[1] & 192) >> 6)) + 1 |
| 1247 |
elif size: |
| 1248 |
raise ValueError("Unsupported WebP file") |
| 1249 |
return _ImageMetadata(width, height) |
| 1250 |
return _ImageMetadata() |
| 1251 |
|
| 1252 |
|
| 1253 |
def get_info(filepath: FileInput, *, size: bool = True, dpi: bool = True, colors: bool = True, |
| 1254 |
exif_rotation: bool = True, channels: bool = True) -> ImageInfo: |
| 1255 |
fhandle, should_close = _open_file(filepath) |
| 1256 |
try: |
| 1257 |
metadata = _read_image_metadata( |
| 1258 |
fhandle, |
| 1259 |
size=size, |
| 1260 |
dpi=dpi, |
| 1261 |
colors=colors, |
| 1262 |
rotation=size, |
| 1263 |
channels=channels, |
| 1264 |
) |
| 1265 |
width, height = metadata.width, metadata.height |
| 1266 |
if exif_rotation and _is_rotation_swapped(metadata.rotation): |
| 1267 |
width, height = height, width |
| 1268 |
return ImageInfo( |
| 1269 |
width=width, |
| 1270 |
height=height, |
| 1271 |
rotation=metadata.rotation, |
| 1272 |
xdpi=metadata.xdpi, |
| 1273 |
ydpi=metadata.ydpi, |
| 1274 |
colors=metadata.colors, |
| 1275 |
channels=metadata.channels, |
| 1276 |
) |
| 1277 |
finally: |
| 1278 |
if should_close: |
| 1279 |
fhandle.close() |
| 1280 |
|
| 1281 |
|
| 1282 |
def get(filepath: FileInput, *, exif_rotation: bool = True) -> Tuple[int, int]: |
| 1283 |
""" |
| 1284 |
Return (width, height) for a given img file content. |
| 1285 |
Set exif_rotation=False to return stored dimensions as-is. |
| 1286 |
:type filepath: Union[bytes, str, pathlib.Path] |
| 1287 |
:rtype Tuple[int, int] |
| 1288 |
""" |
| 1289 |
try: |
| 1290 |
fhandle, should_close = _open_file(filepath) |
| 1291 |
try: |
| 1292 |
metadata = _read_image_metadata( |
| 1293 |
fhandle, |
| 1294 |
size=True, |
| 1295 |
dpi=False, |
| 1296 |
colors=False, |
| 1297 |
rotation=exif_rotation, |
| 1298 |
channels=False, |
| 1299 |
) |
| 1300 |
finally: |
| 1301 |
if should_close: |
| 1302 |
fhandle.close() |
| 1303 |
except Exception: |
| 1304 |
return -1, -1 |
| 1305 |
width, height = metadata.width, metadata.height |
| 1306 |
if exif_rotation and _is_rotation_swapped(metadata.rotation): |
| 1307 |
width, height = height, width |
| 1308 |
return width, height |
| 1309 |
|
| 1310 |
|
| 1311 |
def getDPI(filepath: FileInput) -> Tuple[int, int]: |
| 1312 |
""" |
| 1313 |
Return (x DPI, y DPI) for a given img file content |
| 1314 |
no requirements |
| 1315 |
:type filepath: Union[bytes, str, pathlib.Path] |
| 1316 |
:rtype Tuple[int, int] |
| 1317 |
""" |
| 1318 |
try: |
| 1319 |
fhandle, should_close = _open_file(filepath) |
| 1320 |
try: |
| 1321 |
metadata = _read_image_metadata( |
| 1322 |
fhandle, |
| 1323 |
size=False, |
| 1324 |
dpi=True, |
| 1325 |
colors=False, |
| 1326 |
rotation=False, |
| 1327 |
channels=False, |
| 1328 |
) |
| 1329 |
finally: |
| 1330 |
if should_close: |
| 1331 |
fhandle.close() |
| 1332 |
except Exception: |
| 1333 |
return -1, -1 |
| 1334 |
return metadata.xdpi, metadata.ydpi |