ImageFile.py 29 KB

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