ImageFile.py 24 KB

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