ImageFile.py 21 KB

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