ImageFile.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # base class for image file handlers
  6. #
  7. # history:
  8. # 1995-09-09 fl Created
  9. # 1996-03-11 fl Fixed load mechanism.
  10. # 1996-04-15 fl Added pcx/xbm decoders.
  11. # 1996-04-30 fl Added encoders.
  12. # 1996-12-14 fl Added load helpers
  13. # 1997-01-11 fl Use encode_to_file where possible
  14. # 1997-08-27 fl Flush output in _save
  15. # 1998-03-05 fl Use memory mapping for some modes
  16. # 1999-02-04 fl Use memory mapping also for "I;16" and "I;16B"
  17. # 1999-05-31 fl Added image parser
  18. # 2000-10-12 fl Set readonly flag on memory-mapped images
  19. # 2002-03-20 fl Use better messages for common decoder errors
  20. # 2003-04-21 fl Fall back on mmap/map_buffer if map is not available
  21. # 2003-10-30 fl Added StubImageFile class
  22. # 2004-02-25 fl Made incremental parser more robust
  23. #
  24. # Copyright (c) 1997-2004 by Secret Labs AB
  25. # Copyright (c) 1995-2004 by Fredrik Lundh
  26. #
  27. # See the README file for information on usage and redistribution.
  28. #
  29. from __future__ import annotations
  30. __lazy_modules__ = {"PIL._util", "io", "itertools", "struct"}
  31. import abc
  32. import io
  33. import itertools
  34. import logging
  35. import os
  36. import struct
  37. from typing import NamedTuple, cast
  38. from . import ExifTags, Image
  39. from ._util import DeferredError, is_path
  40. TYPE_CHECKING = False
  41. if TYPE_CHECKING:
  42. from typing import IO, Any, Self
  43. from ._typing import StrOrBytesPath
  44. logger = logging.getLogger(__name__)
  45. MAXBLOCK = 65536
  46. """
  47. By default, Pillow processes image data in blocks. This helps to prevent excessive use
  48. of resources. Codecs may disable this behaviour with ``_pulls_fd`` or ``_pushes_fd``.
  49. When reading an image, this is the number of bytes to read at once.
  50. When writing an image, this is the number of bytes to write at once.
  51. If the image width times 4 is greater, then that will be used instead.
  52. Plugins may also set a greater number.
  53. User code may set this to another number.
  54. """
  55. SAFEBLOCK = 1024 * 1024
  56. LOAD_TRUNCATED_IMAGES = False
  57. """Whether or not to load truncated image files. User code may change this."""
  58. ERRORS = {
  59. -1: "image buffer overrun error",
  60. -2: "decoding error",
  61. -3: "unknown error",
  62. -8: "bad configuration",
  63. -9: "out of memory error",
  64. }
  65. """
  66. Dict of known error codes returned from :meth:`.PyDecoder.decode`,
  67. :meth:`.PyEncoder.encode` :meth:`.PyEncoder.encode_to_pyfd` and
  68. :meth:`.PyEncoder.encode_to_file`.
  69. """
  70. #
  71. # --------------------------------------------------------------------
  72. # Helpers
  73. def _get_oserror(error: int, *, encoder: bool) -> OSError:
  74. try:
  75. msg = Image.core.getcodecstatus(error)
  76. except AttributeError:
  77. msg = ERRORS.get(error)
  78. if not msg:
  79. msg = f"{'encoder' if encoder else 'decoder'} error {error}"
  80. msg += f" when {'writing' if encoder else 'reading'} image file"
  81. return OSError(msg)
  82. def _tilesort(t: _Tile) -> int:
  83. # sort on offset
  84. return t[2]
  85. class _Tile(NamedTuple):
  86. codec_name: str
  87. extents: tuple[int, int, int, int] | None
  88. offset: int = 0
  89. args: tuple[Any, ...] | str | None = None
  90. #
  91. # --------------------------------------------------------------------
  92. # ImageFile base class
  93. class ImageFile(Image.Image, metaclass=abc.ABCMeta):
  94. """Base class for image file format handlers."""
  95. def __init__(
  96. self, fp: StrOrBytesPath | IO[bytes], filename: str | bytes | None = None
  97. ) -> None:
  98. super().__init__()
  99. self._min_frame = 0
  100. self.custom_mimetype: str | None = None
  101. self.tile: list[_Tile] = []
  102. """ A list of tile descriptors """
  103. self.readonly = 1 # until we know better
  104. self.decoderconfig: tuple[Any, ...] = ()
  105. self.decodermaxblock = MAXBLOCK
  106. self.fp: IO[bytes] | None
  107. self._fp: IO[bytes] | DeferredError
  108. if is_path(fp):
  109. # filename
  110. self.fp = open(fp, "rb")
  111. self.filename = os.fspath(fp)
  112. self._exclusive_fp = True
  113. else:
  114. # stream
  115. self.fp = cast("IO[bytes]", fp)
  116. self.filename = filename if filename is not None else ""
  117. # can be overridden
  118. self._exclusive_fp = False
  119. try:
  120. try:
  121. self._open()
  122. if isinstance(self, StubImageFile) and self._handler:
  123. self._handler.open(self)
  124. except (
  125. IndexError, # end of data
  126. TypeError, # end of data (ord)
  127. KeyError, # unsupported mode
  128. EOFError, # got header but not the first frame
  129. struct.error,
  130. ) as v:
  131. raise SyntaxError(v) from v
  132. if not self.mode or (
  133. min(self.size) < 0
  134. if isinstance(self, StubImageFile) and self._handler is None
  135. else min(self.size) <= 0
  136. ):
  137. msg = "not identified by this driver"
  138. raise SyntaxError(msg)
  139. except BaseException:
  140. # close the file only if we have opened it this constructor
  141. if self._exclusive_fp:
  142. self.fp.close()
  143. raise
  144. @abc.abstractmethod
  145. def _open(self) -> None:
  146. pass
  147. def _close_fp(self) -> None:
  148. if getattr(self, "_fp", False) and not isinstance(self._fp, DeferredError):
  149. if self._fp != self.fp:
  150. self._fp.close()
  151. self._fp = DeferredError(ValueError("Operation on closed image"))
  152. if self.fp:
  153. self.fp.close()
  154. # Context manager support
  155. def __exit__(self, *args: object) -> None:
  156. if getattr(self, "_exclusive_fp", False):
  157. self._close_fp()
  158. self.fp = None
  159. def close(self) -> None:
  160. """
  161. Closes the file pointer, if possible.
  162. This operation will destroy the image core and release its memory.
  163. The image data will be unusable afterward.
  164. This function is required to close images that have multiple frames or
  165. have not had their file read and closed by the
  166. :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for
  167. more information.
  168. """
  169. try:
  170. self._close_fp()
  171. self.fp = None
  172. except Exception as msg:
  173. logger.debug("Error closing: %s", msg)
  174. super().close()
  175. def get_child_images(self) -> list[ImageFile]:
  176. child_images = []
  177. exif = self.getexif()
  178. ifds = []
  179. if ExifTags.Base.SubIFDs in exif:
  180. subifd_offsets = exif[ExifTags.Base.SubIFDs]
  181. if subifd_offsets:
  182. if not isinstance(subifd_offsets, tuple):
  183. subifd_offsets = (subifd_offsets,)
  184. ifds = [
  185. (exif._get_ifd_dict(subifd_offset), subifd_offset)
  186. for subifd_offset in subifd_offsets
  187. ]
  188. ifd1 = exif.get_ifd(ExifTags.IFD.IFD1)
  189. if ifd1 and ifd1.get(ExifTags.Base.JpegIFOffset):
  190. assert exif._info is not None
  191. ifds.append((ifd1, exif._info.next))
  192. offset = None
  193. for ifd, ifd_offset in ifds:
  194. assert self.fp is not None
  195. current_offset = self.fp.tell()
  196. if offset is None:
  197. offset = current_offset
  198. fp = self.fp
  199. if ifd is not None:
  200. thumbnail_offset = ifd.get(ExifTags.Base.JpegIFOffset)
  201. if thumbnail_offset is not None:
  202. thumbnail_offset += getattr(self, "_exif_offset", 0)
  203. self.fp.seek(thumbnail_offset)
  204. length = ifd.get(ExifTags.Base.JpegIFByteCount)
  205. assert isinstance(length, int)
  206. data = self.fp.read(length)
  207. fp = io.BytesIO(data)
  208. with Image.open(fp) as im:
  209. from . import TiffImagePlugin
  210. if thumbnail_offset is None and isinstance(
  211. im, TiffImagePlugin.TiffImageFile
  212. ):
  213. im._frame_pos = [ifd_offset]
  214. im._seek(0)
  215. im.load()
  216. child_images.append(im)
  217. if offset is not None:
  218. assert self.fp is not None
  219. self.fp.seek(offset)
  220. return child_images
  221. def get_format_mimetype(self) -> str | None:
  222. if self.custom_mimetype:
  223. return self.custom_mimetype
  224. if self.format is not None:
  225. return Image.MIME.get(self.format.upper())
  226. return None
  227. def __getstate__(self) -> list[Any]:
  228. return super().__getstate__() + [self.filename]
  229. def __setstate__(self, state: list[Any]) -> None:
  230. self.tile = []
  231. if len(state) > 5:
  232. self.filename = state[5]
  233. super().__setstate__(state)
  234. def verify(self) -> None:
  235. """Check file integrity"""
  236. # raise exception if something's wrong. must be called
  237. # directly after open, and closes file when finished.
  238. if self._exclusive_fp and self.fp:
  239. self.fp.close()
  240. self.fp = None
  241. def load(self) -> Image.core.PixelAccess | None:
  242. """Load image data based on tile list"""
  243. if not self.tile and self._im is None:
  244. msg = "cannot load this image"
  245. raise OSError(msg)
  246. pixel = Image.Image.load(self)
  247. if not self.tile:
  248. return pixel
  249. self.map: mmap.mmap | None = None
  250. use_mmap = self.filename and len(self.tile) == 1
  251. assert self.fp is not None
  252. readonly = 0
  253. # look for read/seek overrides
  254. if hasattr(self, "load_read"):
  255. read = self.load_read
  256. # don't use mmap if there are custom read/seek functions
  257. use_mmap = False
  258. else:
  259. read = self.fp.read
  260. if hasattr(self, "load_seek"):
  261. seek = self.load_seek
  262. use_mmap = False
  263. else:
  264. seek = self.fp.seek
  265. if use_mmap:
  266. # try memory mapping
  267. decoder_name, extents, offset, args = self.tile[0]
  268. if isinstance(args, str):
  269. args = (args, 0, 1)
  270. if (
  271. decoder_name == "raw"
  272. and isinstance(args, tuple)
  273. and len(args) >= 3
  274. and args[0] == self.mode
  275. and args[0] in Image._MAPMODES
  276. ):
  277. if offset < 0:
  278. msg = "Tile offset cannot be negative"
  279. raise ValueError(msg)
  280. try:
  281. # use mmap, if possible
  282. import mmap
  283. with open(self.filename) as fp:
  284. self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ)
  285. if self.mode in {"L", "P"}:
  286. pixelsize = 1
  287. elif self.mode.startswith("I;16"):
  288. pixelsize = 2
  289. else:
  290. pixelsize = 4
  291. stride = max(args[1], self.size[0] * pixelsize)
  292. if offset + self.size[1] * stride > self.map.size():
  293. msg = "buffer is not large enough"
  294. raise OSError(msg)
  295. self.im = Image.core.map_buffer(
  296. self.map, self.size, decoder_name, offset, args
  297. )
  298. readonly = 1
  299. # After trashing self.im,
  300. # we might need to reload the palette data.
  301. if self.palette:
  302. self.palette.dirty = 1
  303. except (AttributeError, OSError, ImportError):
  304. self.map = None
  305. self.load_prepare()
  306. err_code = -3 # initialize to unknown error
  307. if not self.map:
  308. # sort tiles in file order
  309. self.tile.sort(key=_tilesort)
  310. # FIXME: This is a hack to handle TIFF's JpegTables tag.
  311. prefix = getattr(self, "tile_prefix", b"")
  312. # Remove consecutive duplicates that only differ by their offset
  313. self.tile = [
  314. list(tiles)[-1]
  315. for _, tiles in itertools.groupby(
  316. self.tile, lambda tile: (tile[0], tile[1], tile[3])
  317. )
  318. ]
  319. for i, (decoder_name, extents, offset, args) in enumerate(self.tile):
  320. seek(offset)
  321. decoder = Image._getdecoder(
  322. self.mode, decoder_name, args, self.decoderconfig
  323. )
  324. try:
  325. decoder.setimage(self.im, extents)
  326. if decoder.pulls_fd:
  327. decoder.setfd(self.fp)
  328. err_code = decoder.decode(b"")[1]
  329. else:
  330. b = prefix
  331. while True:
  332. read_bytes = self.decodermaxblock
  333. if i + 1 < len(self.tile):
  334. next_offset = self.tile[i + 1].offset
  335. if next_offset > offset:
  336. read_bytes = next_offset - offset
  337. try:
  338. s = read(read_bytes)
  339. except (IndexError, struct.error) as e:
  340. # truncated png/gif
  341. if LOAD_TRUNCATED_IMAGES:
  342. break
  343. else:
  344. msg = "image file is truncated"
  345. raise OSError(msg) from e
  346. if not s: # truncated jpeg
  347. if LOAD_TRUNCATED_IMAGES:
  348. break
  349. else:
  350. msg = (
  351. "image file is truncated "
  352. f"({len(b)} bytes not processed)"
  353. )
  354. raise OSError(msg)
  355. b = b + s
  356. n, err_code = decoder.decode(b)
  357. if n < 0:
  358. break
  359. b = b[n:]
  360. finally:
  361. # Need to cleanup here to prevent leaks
  362. decoder.cleanup()
  363. self.tile = []
  364. self.readonly = readonly
  365. self.load_end()
  366. if self._exclusive_fp and self._close_exclusive_fp_after_loading:
  367. self.fp.close()
  368. self.fp = None
  369. if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0:
  370. # still raised if decoder fails to return anything
  371. raise _get_oserror(err_code, encoder=False)
  372. return Image.Image.load(self)
  373. def load_prepare(self) -> None:
  374. # create image memory if necessary
  375. if self._im is None:
  376. self.im = Image.core.new(self.mode, self.size)
  377. # create palette (optional)
  378. if self.mode == "P":
  379. Image.Image.load(self)
  380. def load_end(self) -> None:
  381. # may be overridden
  382. pass
  383. # may be defined for contained formats
  384. # def load_seek(self, pos: int) -> None:
  385. # pass
  386. # may be defined for blocked formats (e.g. PNG)
  387. # def load_read(self, read_bytes: int) -> bytes:
  388. # pass
  389. def _seek_check(self, frame: int) -> bool:
  390. if (
  391. frame < self._min_frame
  392. # Only check upper limit on frames if additional seek operations
  393. # are not required to do so
  394. or (
  395. not (hasattr(self, "_n_frames") and self._n_frames is None)
  396. and frame >= getattr(self, "n_frames") + self._min_frame
  397. )
  398. ):
  399. msg = "attempt to seek outside sequence"
  400. raise EOFError(msg)
  401. return self.tell() != frame
  402. class StubHandler(abc.ABC):
  403. @abc.abstractmethod
  404. def open(self, im: StubImageFile) -> None:
  405. pass
  406. @abc.abstractmethod
  407. def load(self, im: StubImageFile) -> Image.Image:
  408. pass
  409. class StubImageFile(ImageFile):
  410. """
  411. Base class for stub image loaders.
  412. A stub loader is an image loader that can identify files of a
  413. certain format, but relies on external code to load the file.
  414. """
  415. _handler: StubHandler | None = None
  416. def load(self) -> Image.core.PixelAccess | None:
  417. if self._handler is None:
  418. msg = f"cannot find loader for this {self.format} file"
  419. raise OSError(msg)
  420. image = self._handler.load(self)
  421. assert image is not None
  422. # become the other object (!)
  423. self.__class__ = image.__class__ # type: ignore[assignment]
  424. self.__dict__ = image.__dict__
  425. return image.load()
  426. class Parser:
  427. """
  428. Incremental image parser. This class implements the standard
  429. feed/close consumer interface.
  430. """
  431. incremental = None
  432. image: Image.Image | None = None
  433. data: bytes | None = None
  434. decoder: Image.core.ImagingDecoder | PyDecoder | None = None
  435. offset = 0
  436. finished = 0
  437. def reset(self) -> None:
  438. """
  439. (Consumer) Reset the parser. Note that you can only call this
  440. method immediately after you've created a parser; parser
  441. instances cannot be reused.
  442. """
  443. assert self.data is None, "cannot reuse parsers"
  444. def feed(self, data: bytes) -> None:
  445. """
  446. (Consumer) Feed data to the parser.
  447. :param data: A string buffer.
  448. :exception OSError: If the parser failed to parse the image file.
  449. """
  450. # collect data
  451. if self.finished:
  452. return
  453. if self.data is None:
  454. self.data = data
  455. else:
  456. self.data = self.data + data
  457. # parse what we have
  458. if self.decoder:
  459. if self.offset > 0:
  460. # skip header
  461. skip = min(len(self.data), self.offset)
  462. self.data = self.data[skip:]
  463. self.offset = self.offset - skip
  464. if self.offset > 0 or not self.data:
  465. return
  466. n, e = self.decoder.decode(self.data)
  467. if n < 0:
  468. # end of stream
  469. self.data = None
  470. self.finished = 1
  471. if e < 0:
  472. # decoding error
  473. self.image = None
  474. raise _get_oserror(e, encoder=False)
  475. else:
  476. # end of image
  477. return
  478. self.data = self.data[n:]
  479. elif self.image:
  480. # if we end up here with no decoder, this file cannot
  481. # be incrementally parsed. wait until we've gotten all
  482. # available data
  483. pass
  484. else:
  485. # attempt to open this file
  486. try:
  487. with io.BytesIO(self.data) as fp:
  488. im = Image.open(fp)
  489. except OSError:
  490. pass # not enough data
  491. else:
  492. flag = hasattr(im, "load_seek") or hasattr(im, "load_read")
  493. if not flag and len(im.tile) == 1:
  494. # initialize decoder
  495. im.load_prepare()
  496. d, e, o, a = im.tile[0]
  497. im.tile = []
  498. self.decoder = Image._getdecoder(im.mode, d, a, im.decoderconfig)
  499. self.decoder.setimage(im.im, e)
  500. # calculate decoder offset
  501. self.offset = o
  502. if self.offset <= len(self.data):
  503. self.data = self.data[self.offset :]
  504. self.offset = 0
  505. self.image = im
  506. def __enter__(self) -> Self:
  507. return self
  508. def __exit__(self, *args: object) -> None:
  509. self.close()
  510. def close(self) -> Image.Image:
  511. """
  512. (Consumer) Close the stream.
  513. :returns: An image object.
  514. :exception OSError: If the parser failed to parse the image file either
  515. because it cannot be identified or cannot be
  516. decoded.
  517. """
  518. # finish decoding
  519. if self.decoder:
  520. # get rid of what's left in the buffers
  521. self.feed(b"")
  522. self.data = self.decoder = None
  523. if not self.finished:
  524. msg = "image was incomplete"
  525. raise OSError(msg)
  526. if not self.image:
  527. msg = "cannot parse this image"
  528. raise OSError(msg)
  529. if self.data:
  530. # incremental parsing not possible; reopen the file
  531. # not that we have all data
  532. with io.BytesIO(self.data) as fp:
  533. try:
  534. self.image = Image.open(fp)
  535. finally:
  536. self.image.load()
  537. return self.image
  538. # --------------------------------------------------------------------
  539. def _save(im: Image.Image, fp: IO[bytes], tile: list[_Tile], bufsize: int = 0) -> None:
  540. """Helper to save image based on tile list
  541. :param im: Image object.
  542. :param fp: File object.
  543. :param tile: Tile list.
  544. :param bufsize: Optional buffer size
  545. """
  546. im.load()
  547. if not hasattr(im, "encoderconfig"):
  548. im.encoderconfig = ()
  549. tile.sort(key=_tilesort)
  550. # FIXME: make MAXBLOCK a configuration parameter
  551. # It would be great if we could have the encoder specify what it needs
  552. # But, it would need at least the image size in most cases. RawEncode is
  553. # a tricky case.
  554. bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.c
  555. try:
  556. fh = fp.fileno()
  557. fp.flush()
  558. _encode_tile(im, fp, tile, bufsize, fh)
  559. except (AttributeError, io.UnsupportedOperation) as exc:
  560. _encode_tile(im, fp, tile, bufsize, None, exc)
  561. if hasattr(fp, "flush"):
  562. fp.flush()
  563. def _encode_tile(
  564. im: Image.Image,
  565. fp: IO[bytes],
  566. tile: list[_Tile],
  567. bufsize: int,
  568. fh: int | None,
  569. exc: BaseException | None = None,
  570. ) -> None:
  571. for encoder_name, extents, offset, args in tile:
  572. if offset > 0:
  573. fp.seek(offset)
  574. encoder = Image._getencoder(im.mode, encoder_name, args, im.encoderconfig)
  575. try:
  576. encoder.setimage(im.im, extents)
  577. if encoder.pushes_fd:
  578. encoder.setfd(fp)
  579. errcode = encoder.encode_to_pyfd()[1]
  580. else:
  581. if exc:
  582. # compress to Python file-compatible object
  583. while True:
  584. errcode, data = encoder.encode(bufsize)[1:]
  585. fp.write(data)
  586. if errcode:
  587. break
  588. else:
  589. # slight speedup: compress to real file object
  590. assert fh is not None
  591. errcode = encoder.encode_to_file(fh, bufsize)
  592. if errcode < 0:
  593. raise _get_oserror(errcode, encoder=True) from exc
  594. finally:
  595. encoder.cleanup()
  596. def _safe_read(fp: IO[bytes], size: int) -> bytes:
  597. """
  598. Reads large blocks in a safe way. Unlike fp.read(n), this function
  599. doesn't trust the user. If the requested size is larger than
  600. SAFEBLOCK, the file is read block by block.
  601. :param fp: File handle. Must implement a <b>read</b> method.
  602. :param size: Number of bytes to read.
  603. :returns: A string containing <i>size</i> bytes of data.
  604. Raises an OSError if the file is truncated and the read cannot be completed
  605. """
  606. if size <= 0:
  607. return b""
  608. if size <= SAFEBLOCK:
  609. data = fp.read(size)
  610. if len(data) < size:
  611. msg = "Truncated File Read"
  612. raise OSError(msg)
  613. return data
  614. blocks: list[bytes] = []
  615. remaining_size = size
  616. while remaining_size > 0:
  617. block = fp.read(min(remaining_size, SAFEBLOCK))
  618. if not block:
  619. break
  620. blocks.append(block)
  621. remaining_size -= len(block)
  622. if sum(len(block) for block in blocks) < size:
  623. msg = "Truncated File Read"
  624. raise OSError(msg)
  625. return b"".join(blocks)
  626. class PyCodecState:
  627. def __init__(self) -> None:
  628. self.xsize = 0
  629. self.ysize = 0
  630. self.xoff = 0
  631. self.yoff = 0
  632. def extents(self) -> tuple[int, int, int, int]:
  633. return self.xoff, self.yoff, self.xoff + self.xsize, self.yoff + self.ysize
  634. class PyCodec:
  635. fd: IO[bytes] | None
  636. def __init__(self, mode: str, *args: Any) -> None:
  637. self.im: Image.core.ImagingCore | None = None
  638. self.state = PyCodecState()
  639. self.fd = None
  640. self.mode = mode
  641. self.init(args)
  642. def init(self, args: tuple[Any, ...]) -> None:
  643. """
  644. Override to perform codec specific initialization
  645. :param args: Tuple of arg items from the tile entry
  646. :returns: None
  647. """
  648. self.args = args
  649. def cleanup(self) -> None:
  650. """
  651. Override to perform codec specific cleanup
  652. :returns: None
  653. """
  654. pass
  655. def setfd(self, fd: IO[bytes]) -> None:
  656. """
  657. Called from ImageFile to set the Python file-like object
  658. :param fd: A Python file-like object
  659. :returns: None
  660. """
  661. self.fd = fd
  662. def setimage(
  663. self,
  664. im: Image.core.ImagingCore,
  665. extents: tuple[int, int, int, int] | None = None,
  666. ) -> None:
  667. """
  668. Called from ImageFile to set the core output image for the codec
  669. :param im: A core image object
  670. :param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectangle
  671. for this tile
  672. :returns: None
  673. """
  674. # following c code
  675. self.im = im
  676. if extents:
  677. x0, y0, x1, y1 = extents
  678. if x0 < 0 or y0 < 0 or x1 > self.im.size[0] or y1 > self.im.size[1]:
  679. msg = "Tile cannot extend outside image"
  680. raise ValueError(msg)
  681. self.state.xoff = x0
  682. self.state.yoff = y0
  683. self.state.xsize = x1 - x0
  684. self.state.ysize = y1 - y0
  685. else:
  686. self.state.xsize, self.state.ysize = self.im.size
  687. if self.state.xsize <= 0 or self.state.ysize <= 0:
  688. msg = "Size must be positive"
  689. raise ValueError(msg)
  690. class PyDecoder(PyCodec):
  691. """
  692. Python implementation of a format decoder. Override this class and
  693. add the decoding logic in the :meth:`decode` method.
  694. See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`
  695. """
  696. _pulls_fd = False
  697. @property
  698. def pulls_fd(self) -> bool:
  699. return self._pulls_fd
  700. def decode(self, buffer: Image.DecoderInput) -> tuple[int, int]:
  701. """
  702. Override to perform the decoding process.
  703. :param buffer: A bytes object with the data to be decoded.
  704. :returns: A tuple of ``(bytes consumed, errcode)``.
  705. If finished with decoding return -1 for the bytes consumed.
  706. Err codes are from :data:`.ImageFile.ERRORS`.
  707. """
  708. msg = "unavailable in base decoder"
  709. raise NotImplementedError(msg)
  710. def set_as_raw(
  711. self,
  712. data: bytes | bytearray,
  713. rawmode: str | None = None,
  714. extra: tuple[Any, ...] = (),
  715. ) -> None:
  716. """
  717. Convenience method to set the internal image from a stream of raw data
  718. :param data: Bytes to be set
  719. :param rawmode: The rawmode to be used for the decoder.
  720. If not specified, it will default to the mode of the image
  721. :param extra: Extra arguments for the decoder.
  722. :returns: None
  723. """
  724. if not rawmode:
  725. rawmode = self.mode
  726. d = Image._getdecoder(self.mode, "raw", rawmode, extra)
  727. assert self.im is not None
  728. d.setimage(self.im, self.state.extents())
  729. s = d.decode(data)
  730. if s[0] >= 0:
  731. msg = "not enough image data"
  732. raise ValueError(msg)
  733. if s[1] != 0:
  734. msg = "cannot decode image data"
  735. raise ValueError(msg)
  736. class PyEncoder(PyCodec):
  737. """
  738. Python implementation of a format encoder. Override this class and
  739. add the decoding logic in the :meth:`encode` method.
  740. See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`
  741. """
  742. _pushes_fd = False
  743. @property
  744. def pushes_fd(self) -> bool:
  745. return self._pushes_fd
  746. def encode(self, bufsize: int) -> tuple[int, int, bytes]:
  747. """
  748. Override to perform the encoding process.
  749. :param bufsize: Buffer size.
  750. :returns: A tuple of ``(bytes encoded, errcode, bytes)``.
  751. If finished with encoding return 1 for the error code.
  752. Err codes are from :data:`.ImageFile.ERRORS`.
  753. """
  754. msg = "unavailable in base encoder"
  755. raise NotImplementedError(msg)
  756. def encode_to_pyfd(self) -> tuple[int, int]:
  757. """
  758. If ``pushes_fd`` is ``True``, then this method will be used,
  759. and ``encode()`` will only be called once.
  760. :returns: A tuple of ``(bytes consumed, errcode)``.
  761. Err codes are from :data:`.ImageFile.ERRORS`.
  762. """
  763. if not self.pushes_fd:
  764. return 0, -8 # bad configuration
  765. bytes_consumed, errcode, data = self.encode(0)
  766. if data:
  767. assert self.fd is not None
  768. self.fd.write(data)
  769. return bytes_consumed, errcode
  770. def encode_to_file(self, fh: int, bufsize: int) -> int:
  771. """
  772. :param fh: File handle.
  773. :param bufsize: Buffer size.
  774. :returns: If finished successfully, return 0.
  775. Otherwise, return an error code. Err codes are from
  776. :data:`.ImageFile.ERRORS`.
  777. """
  778. errcode = 0
  779. while errcode == 0:
  780. bytes_consumed, errcode, buf = self.encode(bufsize)
  781. if bytes_consumed > 0:
  782. os.write(fh, buf[:bytes_consumed])
  783. return errcode