ImageFile.py 24 KB

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