PngImagePlugin.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # PNG support code
  6. #
  7. # See "PNG (Portable Network Graphics) Specification, version 1.0;
  8. # W3C Recommendation", 1996-10-01, Thomas Boutell (ed.).
  9. #
  10. # history:
  11. # 1996-05-06 fl Created (couldn't resist it)
  12. # 1996-12-14 fl Upgraded, added read and verify support (0.2)
  13. # 1996-12-15 fl Separate PNG stream parser
  14. # 1996-12-29 fl Added write support, added getchunks
  15. # 1996-12-30 fl Eliminated circular references in decoder (0.3)
  16. # 1998-07-12 fl Read/write 16-bit images as mode I (0.4)
  17. # 2001-02-08 fl Added transparency support (from Zircon) (0.5)
  18. # 2001-04-16 fl Don't close data source in "open" method (0.6)
  19. # 2004-02-24 fl Don't even pretend to support interlaced files (0.7)
  20. # 2004-08-31 fl Do basic sanity check on chunk identifiers (0.8)
  21. # 2004-09-20 fl Added PngInfo chunk container
  22. # 2004-12-18 fl Added DPI read support (based on code by Niki Spahiev)
  23. # 2008-08-13 fl Added tRNS support for RGB images
  24. # 2009-03-06 fl Support for preserving ICC profiles (by Florian Hoech)
  25. # 2009-03-08 fl Added zTXT support (from Lowell Alleman)
  26. # 2009-03-29 fl Read interlaced PNG files (from Conrado Porto Lopes Gouvua)
  27. #
  28. # Copyright (c) 1997-2009 by Secret Labs AB
  29. # Copyright (c) 1996 by Fredrik Lundh
  30. #
  31. # See the README file for information on usage and redistribution.
  32. #
  33. from __future__ import annotations
  34. import itertools
  35. import logging
  36. import re
  37. import struct
  38. import warnings
  39. import zlib
  40. from collections.abc import Callable
  41. from enum import IntEnum
  42. from typing import IO, Any, NamedTuple, NoReturn, cast
  43. from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence
  44. from ._binary import i16be as i16
  45. from ._binary import i32be as i32
  46. from ._binary import o8
  47. from ._binary import o16be as o16
  48. from ._binary import o32be as o32
  49. from ._deprecate import deprecate
  50. from ._util import DeferredError
  51. TYPE_CHECKING = False
  52. if TYPE_CHECKING:
  53. from . import _imaging
  54. logger = logging.getLogger(__name__)
  55. is_cid = re.compile(rb"\w\w\w\w").match
  56. _MAGIC = b"\211PNG\r\n\032\n"
  57. _MODES = {
  58. # supported bits/color combinations, and corresponding modes/rawmodes
  59. # Grayscale
  60. (1, 0): ("1", "1"),
  61. (2, 0): ("L", "L;2"),
  62. (4, 0): ("L", "L;4"),
  63. (8, 0): ("L", "L"),
  64. (16, 0): ("I;16", "I;16B"),
  65. # Truecolour
  66. (8, 2): ("RGB", "RGB"),
  67. (16, 2): ("RGB", "RGB;16B"),
  68. # Indexed-colour
  69. (1, 3): ("P", "P;1"),
  70. (2, 3): ("P", "P;2"),
  71. (4, 3): ("P", "P;4"),
  72. (8, 3): ("P", "P"),
  73. # Grayscale with alpha
  74. (8, 4): ("LA", "LA"),
  75. (16, 4): ("RGBA", "LA;16B"), # LA;16B->LA not yet available
  76. # Truecolour with alpha
  77. (8, 6): ("RGBA", "RGBA"),
  78. (16, 6): ("RGBA", "RGBA;16B"),
  79. }
  80. _simple_palette = re.compile(b"^\xff*\x00\xff*$")
  81. MAX_TEXT_CHUNK = ImageFile.SAFEBLOCK
  82. """
  83. Maximum decompressed size for a iTXt or zTXt chunk.
  84. Eliminates decompression bombs where compressed chunks can expand 1000x.
  85. See :ref:`Text in PNG File Format<png-text>`.
  86. """
  87. MAX_TEXT_MEMORY = 64 * MAX_TEXT_CHUNK
  88. """
  89. Set the maximum total text chunk size.
  90. See :ref:`Text in PNG File Format<png-text>`.
  91. """
  92. # APNG frame disposal modes
  93. class Disposal(IntEnum):
  94. OP_NONE = 0
  95. """
  96. No disposal is done on this frame before rendering the next frame.
  97. See :ref:`Saving APNG sequences<apng-saving>`.
  98. """
  99. OP_BACKGROUND = 1
  100. """
  101. This frame’s modified region is cleared to fully transparent black before rendering
  102. the next frame.
  103. See :ref:`Saving APNG sequences<apng-saving>`.
  104. """
  105. OP_PREVIOUS = 2
  106. """
  107. This frame’s modified region is reverted to the previous frame’s contents before
  108. rendering the next frame.
  109. See :ref:`Saving APNG sequences<apng-saving>`.
  110. """
  111. # APNG frame blend modes
  112. class Blend(IntEnum):
  113. OP_SOURCE = 0
  114. """
  115. All color components of this frame, including alpha, overwrite the previous output
  116. image contents.
  117. See :ref:`Saving APNG sequences<apng-saving>`.
  118. """
  119. OP_OVER = 1
  120. """
  121. This frame should be alpha composited with the previous output image contents.
  122. See :ref:`Saving APNG sequences<apng-saving>`.
  123. """
  124. def _safe_zlib_decompress(s: bytes) -> bytes:
  125. dobj = zlib.decompressobj()
  126. plaintext = dobj.decompress(s, MAX_TEXT_CHUNK)
  127. if dobj.unconsumed_tail:
  128. msg = "Decompressed data too large for PngImagePlugin.MAX_TEXT_CHUNK"
  129. raise ValueError(msg)
  130. return plaintext
  131. def _crc32(data: bytes, seed: int = 0) -> int:
  132. return zlib.crc32(data, seed) & 0xFFFFFFFF
  133. # --------------------------------------------------------------------
  134. # Support classes. Suitable for PNG and related formats like MNG etc.
  135. class ChunkStream:
  136. def __init__(self, fp: IO[bytes]) -> None:
  137. self.fp: IO[bytes] | None = fp
  138. self.queue: list[tuple[bytes, int, int]] | None = []
  139. def read(self) -> tuple[bytes, int, int]:
  140. """Fetch a new chunk. Returns header information."""
  141. cid = None
  142. assert self.fp is not None
  143. if self.queue:
  144. cid, pos, length = self.queue.pop()
  145. self.fp.seek(pos)
  146. else:
  147. s = self.fp.read(8)
  148. cid = s[4:]
  149. pos = self.fp.tell()
  150. length = i32(s)
  151. if not is_cid(cid):
  152. if not ImageFile.LOAD_TRUNCATED_IMAGES:
  153. msg = f"broken PNG file (chunk {repr(cid)})"
  154. raise SyntaxError(msg)
  155. return cid, pos, length
  156. def __enter__(self) -> ChunkStream:
  157. return self
  158. def __exit__(self, *args: object) -> None:
  159. self.close()
  160. def close(self) -> None:
  161. self.queue = self.fp = None
  162. def push(self, cid: bytes, pos: int, length: int) -> None:
  163. assert self.queue is not None
  164. self.queue.append((cid, pos, length))
  165. def call(self, cid: bytes, pos: int, length: int) -> bytes:
  166. """Call the appropriate chunk handler"""
  167. logger.debug("STREAM %r %s %s", cid, pos, length)
  168. return getattr(self, f"chunk_{cid.decode('ascii')}")(pos, length)
  169. def crc(self, cid: bytes, data: bytes) -> None:
  170. """Read and verify checksum"""
  171. # Skip CRC checks for ancillary chunks if allowed to load truncated
  172. # images
  173. # 5th byte of first char is 1 [specs, section 5.4]
  174. if ImageFile.LOAD_TRUNCATED_IMAGES and (cid[0] >> 5 & 1):
  175. self.crc_skip(cid, data)
  176. return
  177. assert self.fp is not None
  178. try:
  179. crc1 = _crc32(data, _crc32(cid))
  180. crc2 = i32(self.fp.read(4))
  181. if crc1 != crc2:
  182. msg = f"broken PNG file (bad header checksum in {repr(cid)})"
  183. raise SyntaxError(msg)
  184. except struct.error as e:
  185. msg = f"broken PNG file (incomplete checksum in {repr(cid)})"
  186. raise SyntaxError(msg) from e
  187. def crc_skip(self, cid: bytes, data: bytes) -> None:
  188. """Read checksum"""
  189. assert self.fp is not None
  190. self.fp.read(4)
  191. def verify(self, endchunk: bytes = b"IEND") -> list[bytes]:
  192. # Simple approach; just calculate checksum for all remaining
  193. # blocks. Must be called directly after open.
  194. cids = []
  195. assert self.fp is not None
  196. while True:
  197. try:
  198. cid, pos, length = self.read()
  199. except struct.error as e:
  200. msg = "truncated PNG file"
  201. raise OSError(msg) from e
  202. if cid == endchunk:
  203. break
  204. self.crc(cid, ImageFile._safe_read(self.fp, length))
  205. cids.append(cid)
  206. return cids
  207. class iTXt(str):
  208. """
  209. Subclass of string to allow iTXt chunks to look like strings while
  210. keeping their extra information
  211. """
  212. lang: str | bytes | None
  213. tkey: str | bytes | None
  214. @staticmethod
  215. def __new__(
  216. cls, text: str, lang: str | None = None, tkey: str | None = None
  217. ) -> iTXt:
  218. """
  219. :param cls: the class to use when creating the instance
  220. :param text: value for this key
  221. :param lang: language code
  222. :param tkey: UTF-8 version of the key name
  223. """
  224. self = str.__new__(cls, text)
  225. self.lang = lang
  226. self.tkey = tkey
  227. return self
  228. class PngInfo:
  229. """
  230. PNG chunk container (for use with save(pnginfo=))
  231. """
  232. def __init__(self) -> None:
  233. self.chunks: list[tuple[bytes, bytes, bool]] = []
  234. def add(self, cid: bytes, data: bytes, after_idat: bool = False) -> None:
  235. """Appends an arbitrary chunk. Use with caution.
  236. :param cid: a byte string, 4 bytes long.
  237. :param data: a byte string of the encoded data
  238. :param after_idat: for use with private chunks. Whether the chunk
  239. should be written after IDAT
  240. """
  241. self.chunks.append((cid, data, after_idat))
  242. def add_itxt(
  243. self,
  244. key: str | bytes,
  245. value: str | bytes,
  246. lang: str | bytes = "",
  247. tkey: str | bytes = "",
  248. zip: bool = False,
  249. ) -> None:
  250. """Appends an iTXt chunk.
  251. :param key: latin-1 encodable text key name
  252. :param value: value for this key
  253. :param lang: language code
  254. :param tkey: UTF-8 version of the key name
  255. :param zip: compression flag
  256. """
  257. if not isinstance(key, bytes):
  258. key = key.encode("latin-1", "strict")
  259. if not isinstance(value, bytes):
  260. value = value.encode("utf-8", "strict")
  261. if not isinstance(lang, bytes):
  262. lang = lang.encode("utf-8", "strict")
  263. if not isinstance(tkey, bytes):
  264. tkey = tkey.encode("utf-8", "strict")
  265. if zip:
  266. self.add(
  267. b"iTXt",
  268. key + b"\0\x01\0" + lang + b"\0" + tkey + b"\0" + zlib.compress(value),
  269. )
  270. else:
  271. self.add(b"iTXt", key + b"\0\0\0" + lang + b"\0" + tkey + b"\0" + value)
  272. def add_text(
  273. self, key: str | bytes, value: str | bytes | iTXt, zip: bool = False
  274. ) -> None:
  275. """Appends a text chunk.
  276. :param key: latin-1 encodable text key name
  277. :param value: value for this key, text or an
  278. :py:class:`PIL.PngImagePlugin.iTXt` instance
  279. :param zip: compression flag
  280. """
  281. if isinstance(value, iTXt):
  282. return self.add_itxt(
  283. key,
  284. value,
  285. value.lang if value.lang is not None else b"",
  286. value.tkey if value.tkey is not None else b"",
  287. zip=zip,
  288. )
  289. # The tEXt chunk stores latin-1 text
  290. if not isinstance(value, bytes):
  291. try:
  292. value = value.encode("latin-1", "strict")
  293. except UnicodeError:
  294. return self.add_itxt(key, value, zip=zip)
  295. if not isinstance(key, bytes):
  296. key = key.encode("latin-1", "strict")
  297. if zip:
  298. self.add(b"zTXt", key + b"\0\0" + zlib.compress(value))
  299. else:
  300. self.add(b"tEXt", key + b"\0" + value)
  301. # --------------------------------------------------------------------
  302. # PNG image stream (IHDR/IEND)
  303. class _RewindState(NamedTuple):
  304. info: dict[str | tuple[int, int], Any]
  305. tile: list[ImageFile._Tile]
  306. seq_num: int | None
  307. class PngStream(ChunkStream):
  308. def __init__(self, fp: IO[bytes]) -> None:
  309. super().__init__(fp)
  310. # local copies of Image attributes
  311. self.im_info: dict[str | tuple[int, int], Any] = {}
  312. self.im_text: dict[str, str | iTXt] = {}
  313. self.im_size = (0, 0)
  314. self.im_mode = ""
  315. self.im_tile: list[ImageFile._Tile] = []
  316. self.im_palette: tuple[str, bytes] | None = None
  317. self.im_custom_mimetype: str | None = None
  318. self.im_n_frames: int | None = None
  319. self._seq_num: int | None = None
  320. self.rewind_state = _RewindState({}, [], None)
  321. self.text_memory = 0
  322. def check_text_memory(self, chunklen: int) -> None:
  323. self.text_memory += chunklen
  324. if self.text_memory > MAX_TEXT_MEMORY:
  325. msg = (
  326. "Too much memory used in text chunks: "
  327. f"{self.text_memory}>MAX_TEXT_MEMORY"
  328. )
  329. raise ValueError(msg)
  330. def save_rewind(self) -> None:
  331. self.rewind_state = _RewindState(
  332. self.im_info.copy(),
  333. self.im_tile,
  334. self._seq_num,
  335. )
  336. def rewind(self) -> None:
  337. self.im_info = self.rewind_state.info.copy()
  338. self.im_tile = self.rewind_state.tile
  339. self._seq_num = self.rewind_state.seq_num
  340. def chunk_iCCP(self, pos: int, length: int) -> bytes:
  341. # ICC profile
  342. assert self.fp is not None
  343. s = ImageFile._safe_read(self.fp, length)
  344. # according to PNG spec, the iCCP chunk contains:
  345. # Profile name 1-79 bytes (character string)
  346. # Null separator 1 byte (null character)
  347. # Compression method 1 byte (0)
  348. # Compressed profile n bytes (zlib with deflate compression)
  349. i = s.find(b"\0")
  350. logger.debug("iCCP profile name %r", s[:i])
  351. comp_method = s[i + 1]
  352. logger.debug("Compression method %s", comp_method)
  353. if comp_method != 0:
  354. msg = f"Unknown compression method {comp_method} in iCCP chunk"
  355. raise SyntaxError(msg)
  356. try:
  357. icc_profile = _safe_zlib_decompress(s[i + 2 :])
  358. except ValueError:
  359. if ImageFile.LOAD_TRUNCATED_IMAGES:
  360. icc_profile = None
  361. else:
  362. raise
  363. except zlib.error:
  364. icc_profile = None # FIXME
  365. self.im_info["icc_profile"] = icc_profile
  366. return s
  367. def chunk_IHDR(self, pos: int, length: int) -> bytes:
  368. # image header
  369. assert self.fp is not None
  370. s = ImageFile._safe_read(self.fp, length)
  371. if length < 13:
  372. if ImageFile.LOAD_TRUNCATED_IMAGES:
  373. return s
  374. msg = "Truncated IHDR chunk"
  375. raise ValueError(msg)
  376. self.im_size = i32(s, 0), i32(s, 4)
  377. try:
  378. self.im_mode, self.im_rawmode = _MODES[(s[8], s[9])]
  379. except Exception:
  380. pass
  381. if s[12]:
  382. self.im_info["interlace"] = 1
  383. if s[11]:
  384. msg = "unknown filter category"
  385. raise SyntaxError(msg)
  386. return s
  387. def chunk_IDAT(self, pos: int, length: int) -> NoReturn:
  388. # image data
  389. if "bbox" in self.im_info:
  390. tile = [ImageFile._Tile("zip", self.im_info["bbox"], pos, self.im_rawmode)]
  391. else:
  392. if self.im_n_frames is not None:
  393. self.im_info["default_image"] = True
  394. tile = [ImageFile._Tile("zip", (0, 0) + self.im_size, pos, self.im_rawmode)]
  395. self.im_tile = tile
  396. self.im_idat = length
  397. msg = "image data found"
  398. raise EOFError(msg)
  399. def chunk_IEND(self, pos: int, length: int) -> NoReturn:
  400. msg = "end of PNG image"
  401. raise EOFError(msg)
  402. def chunk_PLTE(self, pos: int, length: int) -> bytes:
  403. # palette
  404. assert self.fp is not None
  405. s = ImageFile._safe_read(self.fp, length)
  406. if self.im_mode == "P":
  407. self.im_palette = "RGB", s
  408. return s
  409. def chunk_tRNS(self, pos: int, length: int) -> bytes:
  410. # transparency
  411. assert self.fp is not None
  412. s = ImageFile._safe_read(self.fp, length)
  413. if self.im_mode == "P":
  414. if _simple_palette.match(s):
  415. # tRNS contains only one full-transparent entry,
  416. # other entries are full opaque
  417. i = s.find(b"\0")
  418. if i >= 0:
  419. self.im_info["transparency"] = i
  420. else:
  421. # otherwise, we have a byte string with one alpha value
  422. # for each palette entry
  423. self.im_info["transparency"] = s
  424. elif self.im_mode in ("1", "L", "I;16"):
  425. self.im_info["transparency"] = i16(s)
  426. elif self.im_mode == "RGB":
  427. self.im_info["transparency"] = i16(s), i16(s, 2), i16(s, 4)
  428. return s
  429. def chunk_gAMA(self, pos: int, length: int) -> bytes:
  430. # gamma setting
  431. assert self.fp is not None
  432. s = ImageFile._safe_read(self.fp, length)
  433. self.im_info["gamma"] = i32(s) / 100000.0
  434. return s
  435. def chunk_cHRM(self, pos: int, length: int) -> bytes:
  436. # chromaticity, 8 unsigned ints, actual value is scaled by 100,000
  437. # WP x,y, Red x,y, Green x,y Blue x,y
  438. assert self.fp is not None
  439. s = ImageFile._safe_read(self.fp, length)
  440. raw_vals = struct.unpack(f">{len(s) // 4}I", s)
  441. self.im_info["chromaticity"] = tuple(elt / 100000.0 for elt in raw_vals)
  442. return s
  443. def chunk_sRGB(self, pos: int, length: int) -> bytes:
  444. # srgb rendering intent, 1 byte
  445. # 0 perceptual
  446. # 1 relative colorimetric
  447. # 2 saturation
  448. # 3 absolute colorimetric
  449. assert self.fp is not None
  450. s = ImageFile._safe_read(self.fp, length)
  451. if length < 1:
  452. if ImageFile.LOAD_TRUNCATED_IMAGES:
  453. return s
  454. msg = "Truncated sRGB chunk"
  455. raise ValueError(msg)
  456. self.im_info["srgb"] = s[0]
  457. return s
  458. def chunk_pHYs(self, pos: int, length: int) -> bytes:
  459. # pixels per unit
  460. assert self.fp is not None
  461. s = ImageFile._safe_read(self.fp, length)
  462. if length < 9:
  463. if ImageFile.LOAD_TRUNCATED_IMAGES:
  464. return s
  465. msg = "Truncated pHYs chunk"
  466. raise ValueError(msg)
  467. px, py = i32(s, 0), i32(s, 4)
  468. unit = s[8]
  469. if unit == 1: # meter
  470. dpi = px * 0.0254, py * 0.0254
  471. self.im_info["dpi"] = dpi
  472. elif unit == 0:
  473. self.im_info["aspect"] = px, py
  474. return s
  475. def chunk_tEXt(self, pos: int, length: int) -> bytes:
  476. # text
  477. assert self.fp is not None
  478. s = ImageFile._safe_read(self.fp, length)
  479. try:
  480. k, v = s.split(b"\0", 1)
  481. except ValueError:
  482. # fallback for broken tEXt tags
  483. k = s
  484. v = b""
  485. if k:
  486. k_str = k.decode("latin-1", "strict")
  487. v_str = v.decode("latin-1", "replace")
  488. self.im_info[k_str] = v if k == b"exif" else v_str
  489. self.im_text[k_str] = v_str
  490. self.check_text_memory(len(v_str))
  491. return s
  492. def chunk_zTXt(self, pos: int, length: int) -> bytes:
  493. # compressed text
  494. assert self.fp is not None
  495. s = ImageFile._safe_read(self.fp, length)
  496. try:
  497. k, v = s.split(b"\0", 1)
  498. except ValueError:
  499. k = s
  500. v = b""
  501. if v:
  502. comp_method = v[0]
  503. else:
  504. comp_method = 0
  505. if comp_method != 0:
  506. msg = f"Unknown compression method {comp_method} in zTXt chunk"
  507. raise SyntaxError(msg)
  508. try:
  509. v = _safe_zlib_decompress(v[1:])
  510. except ValueError:
  511. if ImageFile.LOAD_TRUNCATED_IMAGES:
  512. v = b""
  513. else:
  514. raise
  515. except zlib.error:
  516. v = b""
  517. if k:
  518. k_str = k.decode("latin-1", "strict")
  519. v_str = v.decode("latin-1", "replace")
  520. self.im_info[k_str] = self.im_text[k_str] = v_str
  521. self.check_text_memory(len(v_str))
  522. return s
  523. def chunk_iTXt(self, pos: int, length: int) -> bytes:
  524. # international text
  525. assert self.fp is not None
  526. r = s = ImageFile._safe_read(self.fp, length)
  527. try:
  528. k, r = r.split(b"\0", 1)
  529. except ValueError:
  530. return s
  531. if len(r) < 2:
  532. return s
  533. cf, cm, r = r[0], r[1], r[2:]
  534. try:
  535. lang, tk, v = r.split(b"\0", 2)
  536. except ValueError:
  537. return s
  538. if cf != 0:
  539. if cm == 0:
  540. try:
  541. v = _safe_zlib_decompress(v)
  542. except ValueError:
  543. if ImageFile.LOAD_TRUNCATED_IMAGES:
  544. return s
  545. else:
  546. raise
  547. except zlib.error:
  548. return s
  549. else:
  550. return s
  551. if k == b"XML:com.adobe.xmp":
  552. self.im_info["xmp"] = v
  553. try:
  554. k_str = k.decode("latin-1", "strict")
  555. lang_str = lang.decode("utf-8", "strict")
  556. tk_str = tk.decode("utf-8", "strict")
  557. v_str = v.decode("utf-8", "strict")
  558. except UnicodeError:
  559. return s
  560. self.im_info[k_str] = self.im_text[k_str] = iTXt(v_str, lang_str, tk_str)
  561. self.check_text_memory(len(v_str))
  562. return s
  563. def chunk_eXIf(self, pos: int, length: int) -> bytes:
  564. assert self.fp is not None
  565. s = ImageFile._safe_read(self.fp, length)
  566. self.im_info["exif"] = b"Exif\x00\x00" + s
  567. return s
  568. # APNG chunks
  569. def chunk_acTL(self, pos: int, length: int) -> bytes:
  570. assert self.fp is not None
  571. s = ImageFile._safe_read(self.fp, length)
  572. if length < 8:
  573. if ImageFile.LOAD_TRUNCATED_IMAGES:
  574. return s
  575. msg = "APNG contains truncated acTL chunk"
  576. raise ValueError(msg)
  577. if self.im_n_frames is not None:
  578. self.im_n_frames = None
  579. warnings.warn("Invalid APNG, will use default PNG image if possible")
  580. return s
  581. n_frames = i32(s)
  582. if n_frames == 0 or n_frames > 0x80000000:
  583. warnings.warn("Invalid APNG, will use default PNG image if possible")
  584. return s
  585. self.im_n_frames = n_frames
  586. self.im_info["loop"] = i32(s, 4)
  587. self.im_custom_mimetype = "image/apng"
  588. return s
  589. def chunk_fcTL(self, pos: int, length: int) -> bytes:
  590. assert self.fp is not None
  591. s = ImageFile._safe_read(self.fp, length)
  592. if length < 26:
  593. if ImageFile.LOAD_TRUNCATED_IMAGES:
  594. return s
  595. msg = "APNG contains truncated fcTL chunk"
  596. raise ValueError(msg)
  597. seq = i32(s)
  598. if (self._seq_num is None and seq != 0) or (
  599. self._seq_num is not None and self._seq_num != seq - 1
  600. ):
  601. msg = "APNG contains frame sequence errors"
  602. raise SyntaxError(msg)
  603. self._seq_num = seq
  604. width, height = i32(s, 4), i32(s, 8)
  605. px, py = i32(s, 12), i32(s, 16)
  606. im_w, im_h = self.im_size
  607. if px + width > im_w or py + height > im_h:
  608. msg = "APNG contains invalid frames"
  609. raise SyntaxError(msg)
  610. self.im_info["bbox"] = (px, py, px + width, py + height)
  611. delay_num, delay_den = i16(s, 20), i16(s, 22)
  612. if delay_den == 0:
  613. delay_den = 100
  614. self.im_info["duration"] = float(delay_num) / float(delay_den) * 1000
  615. self.im_info["disposal"] = s[24]
  616. self.im_info["blend"] = s[25]
  617. return s
  618. def chunk_fdAT(self, pos: int, length: int) -> bytes:
  619. assert self.fp is not None
  620. if length < 4:
  621. if ImageFile.LOAD_TRUNCATED_IMAGES:
  622. s = ImageFile._safe_read(self.fp, length)
  623. return s
  624. msg = "APNG contains truncated fDAT chunk"
  625. raise ValueError(msg)
  626. s = ImageFile._safe_read(self.fp, 4)
  627. seq = i32(s)
  628. if self._seq_num != seq - 1:
  629. msg = "APNG contains frame sequence errors"
  630. raise SyntaxError(msg)
  631. self._seq_num = seq
  632. return self.chunk_IDAT(pos + 4, length - 4)
  633. # --------------------------------------------------------------------
  634. # PNG reader
  635. def _accept(prefix: bytes) -> bool:
  636. return prefix.startswith(_MAGIC)
  637. ##
  638. # Image plugin for PNG images.
  639. class PngImageFile(ImageFile.ImageFile):
  640. format = "PNG"
  641. format_description = "Portable network graphics"
  642. def _open(self) -> None:
  643. if not _accept(self.fp.read(8)):
  644. msg = "not a PNG file"
  645. raise SyntaxError(msg)
  646. self._fp = self.fp
  647. self.__frame = 0
  648. #
  649. # Parse headers up to the first IDAT or fDAT chunk
  650. self.private_chunks: list[tuple[bytes, bytes] | tuple[bytes, bytes, bool]] = []
  651. self.png: PngStream | None = PngStream(self.fp)
  652. while True:
  653. #
  654. # get next chunk
  655. cid, pos, length = self.png.read()
  656. try:
  657. s = self.png.call(cid, pos, length)
  658. except EOFError:
  659. break
  660. except AttributeError:
  661. logger.debug("%r %s %s (unknown)", cid, pos, length)
  662. s = ImageFile._safe_read(self.fp, length)
  663. if cid[1:2].islower():
  664. self.private_chunks.append((cid, s))
  665. self.png.crc(cid, s)
  666. #
  667. # Copy relevant attributes from the PngStream. An alternative
  668. # would be to let the PngStream class modify these attributes
  669. # directly, but that introduces circular references which are
  670. # difficult to break if things go wrong in the decoder...
  671. # (believe me, I've tried ;-)
  672. self._mode = self.png.im_mode
  673. self._size = self.png.im_size
  674. self.info = self.png.im_info
  675. self._text: dict[str, str | iTXt] | None = None
  676. self.tile = self.png.im_tile
  677. self.custom_mimetype = self.png.im_custom_mimetype
  678. self.n_frames = self.png.im_n_frames or 1
  679. self.default_image = self.info.get("default_image", False)
  680. if self.png.im_palette:
  681. rawmode, data = self.png.im_palette
  682. self.palette = ImagePalette.raw(rawmode, data)
  683. if cid == b"fdAT":
  684. self.__prepare_idat = length - 4
  685. else:
  686. self.__prepare_idat = length # used by load_prepare()
  687. if self.png.im_n_frames is not None:
  688. self._close_exclusive_fp_after_loading = False
  689. self.png.save_rewind()
  690. self.__rewind_idat = self.__prepare_idat
  691. self.__rewind = self._fp.tell()
  692. if self.default_image:
  693. # IDAT chunk contains default image and not first animation frame
  694. self.n_frames += 1
  695. self._seek(0)
  696. self.is_animated = self.n_frames > 1
  697. @property
  698. def text(self) -> dict[str, str | iTXt]:
  699. # experimental
  700. if self._text is None:
  701. # iTxt, tEXt and zTXt chunks may appear at the end of the file
  702. # So load the file to ensure that they are read
  703. if self.is_animated:
  704. frame = self.__frame
  705. # for APNG, seek to the final frame before loading
  706. self.seek(self.n_frames - 1)
  707. self.load()
  708. if self.is_animated:
  709. self.seek(frame)
  710. assert self._text is not None
  711. return self._text
  712. def verify(self) -> None:
  713. """Verify PNG file"""
  714. if self.fp is None:
  715. msg = "verify must be called directly after open"
  716. raise RuntimeError(msg)
  717. # back up to beginning of IDAT block
  718. self.fp.seek(self.tile[0][2] - 8)
  719. assert self.png is not None
  720. self.png.verify()
  721. self.png.close()
  722. if self._exclusive_fp:
  723. self.fp.close()
  724. self.fp = None
  725. def seek(self, frame: int) -> None:
  726. if not self._seek_check(frame):
  727. return
  728. if frame < self.__frame:
  729. self._seek(0, True)
  730. last_frame = self.__frame
  731. for f in range(self.__frame + 1, frame + 1):
  732. try:
  733. self._seek(f)
  734. except EOFError as e:
  735. self.seek(last_frame)
  736. msg = "no more images in APNG file"
  737. raise EOFError(msg) from e
  738. def _seek(self, frame: int, rewind: bool = False) -> None:
  739. assert self.png is not None
  740. if isinstance(self._fp, DeferredError):
  741. raise self._fp.ex
  742. self.dispose: _imaging.ImagingCore | None
  743. dispose_extent = None
  744. if frame == 0:
  745. if rewind:
  746. self._fp.seek(self.__rewind)
  747. self.png.rewind()
  748. self.__prepare_idat = self.__rewind_idat
  749. self._im = None
  750. self.info = self.png.im_info
  751. self.tile = self.png.im_tile
  752. self.fp = self._fp
  753. self._prev_im = None
  754. self.dispose = None
  755. self.default_image = self.info.get("default_image", False)
  756. self.dispose_op = self.info.get("disposal")
  757. self.blend_op = self.info.get("blend")
  758. dispose_extent = self.info.get("bbox")
  759. self.__frame = 0
  760. else:
  761. if frame != self.__frame + 1:
  762. msg = f"cannot seek to frame {frame}"
  763. raise ValueError(msg)
  764. # ensure previous frame was loaded
  765. self.load()
  766. if self.dispose:
  767. self.im.paste(self.dispose, self.dispose_extent)
  768. self._prev_im = self.im.copy()
  769. self.fp = self._fp
  770. # advance to the next frame
  771. if self.__prepare_idat:
  772. ImageFile._safe_read(self.fp, self.__prepare_idat)
  773. self.__prepare_idat = 0
  774. frame_start = False
  775. while True:
  776. self.fp.read(4) # CRC
  777. try:
  778. cid, pos, length = self.png.read()
  779. except (struct.error, SyntaxError):
  780. break
  781. if cid == b"IEND":
  782. msg = "No more images in APNG file"
  783. raise EOFError(msg)
  784. if cid == b"fcTL":
  785. if frame_start:
  786. # there must be at least one fdAT chunk between fcTL chunks
  787. msg = "APNG missing frame data"
  788. raise SyntaxError(msg)
  789. frame_start = True
  790. try:
  791. self.png.call(cid, pos, length)
  792. except UnicodeDecodeError:
  793. break
  794. except EOFError:
  795. if cid == b"fdAT":
  796. length -= 4
  797. if frame_start:
  798. self.__prepare_idat = length
  799. break
  800. ImageFile._safe_read(self.fp, length)
  801. except AttributeError:
  802. logger.debug("%r %s %s (unknown)", cid, pos, length)
  803. ImageFile._safe_read(self.fp, length)
  804. self.__frame = frame
  805. self.tile = self.png.im_tile
  806. self.dispose_op = self.info.get("disposal")
  807. self.blend_op = self.info.get("blend")
  808. dispose_extent = self.info.get("bbox")
  809. if not self.tile:
  810. msg = "image not found in APNG frame"
  811. raise EOFError(msg)
  812. if dispose_extent:
  813. self.dispose_extent: tuple[float, float, float, float] = dispose_extent
  814. # setup frame disposal (actual disposal done when needed in the next _seek())
  815. if self._prev_im is None and self.dispose_op == Disposal.OP_PREVIOUS:
  816. self.dispose_op = Disposal.OP_BACKGROUND
  817. self.dispose = None
  818. if self.dispose_op == Disposal.OP_PREVIOUS:
  819. if self._prev_im:
  820. self.dispose = self._prev_im.copy()
  821. self.dispose = self._crop(self.dispose, self.dispose_extent)
  822. elif self.dispose_op == Disposal.OP_BACKGROUND:
  823. self.dispose = Image.core.fill(self.mode, self.size)
  824. self.dispose = self._crop(self.dispose, self.dispose_extent)
  825. def tell(self) -> int:
  826. return self.__frame
  827. def load_prepare(self) -> None:
  828. """internal: prepare to read PNG file"""
  829. if self.info.get("interlace"):
  830. self.decoderconfig = self.decoderconfig + (1,)
  831. self.__idat = self.__prepare_idat # used by load_read()
  832. ImageFile.ImageFile.load_prepare(self)
  833. def load_read(self, read_bytes: int) -> bytes:
  834. """internal: read more image data"""
  835. assert self.png is not None
  836. while self.__idat == 0:
  837. # end of chunk, skip forward to next one
  838. self.fp.read(4) # CRC
  839. cid, pos, length = self.png.read()
  840. if cid not in [b"IDAT", b"DDAT", b"fdAT"]:
  841. self.png.push(cid, pos, length)
  842. return b""
  843. if cid == b"fdAT":
  844. try:
  845. self.png.call(cid, pos, length)
  846. except EOFError:
  847. pass
  848. self.__idat = length - 4 # sequence_num has already been read
  849. else:
  850. self.__idat = length # empty chunks are allowed
  851. # read more data from this chunk
  852. if read_bytes <= 0:
  853. read_bytes = self.__idat
  854. else:
  855. read_bytes = min(read_bytes, self.__idat)
  856. self.__idat = self.__idat - read_bytes
  857. return self.fp.read(read_bytes)
  858. def load_end(self) -> None:
  859. """internal: finished reading image data"""
  860. assert self.png is not None
  861. if self.__idat != 0:
  862. self.fp.read(self.__idat)
  863. while True:
  864. self.fp.read(4) # CRC
  865. try:
  866. cid, pos, length = self.png.read()
  867. except (struct.error, SyntaxError):
  868. break
  869. if cid == b"IEND":
  870. break
  871. elif cid == b"fcTL" and self.is_animated:
  872. # start of the next frame, stop reading
  873. self.__prepare_idat = 0
  874. self.png.push(cid, pos, length)
  875. break
  876. try:
  877. self.png.call(cid, pos, length)
  878. except UnicodeDecodeError:
  879. break
  880. except EOFError:
  881. if cid == b"fdAT":
  882. length -= 4
  883. try:
  884. ImageFile._safe_read(self.fp, length)
  885. except OSError as e:
  886. if ImageFile.LOAD_TRUNCATED_IMAGES:
  887. break
  888. else:
  889. raise e
  890. except AttributeError:
  891. logger.debug("%r %s %s (unknown)", cid, pos, length)
  892. s = ImageFile._safe_read(self.fp, length)
  893. if cid[1:2].islower():
  894. self.private_chunks.append((cid, s, True))
  895. self._text = self.png.im_text
  896. if not self.is_animated:
  897. self.png.close()
  898. self.png = None
  899. else:
  900. if self._prev_im and self.blend_op == Blend.OP_OVER:
  901. updated = self._crop(self.im, self.dispose_extent)
  902. if self.im.mode == "RGB" and "transparency" in self.info:
  903. mask = updated.convert_transparent(
  904. "RGBA", self.info["transparency"]
  905. )
  906. else:
  907. if self.im.mode == "P" and "transparency" in self.info:
  908. t = self.info["transparency"]
  909. if isinstance(t, bytes):
  910. updated.putpalettealphas(t)
  911. elif isinstance(t, int):
  912. updated.putpalettealpha(t)
  913. mask = updated.convert("RGBA")
  914. self._prev_im.paste(updated, self.dispose_extent, mask)
  915. self.im = self._prev_im
  916. def _getexif(self) -> dict[int, Any] | None:
  917. if "exif" not in self.info:
  918. self.load()
  919. if "exif" not in self.info and "Raw profile type exif" not in self.info:
  920. return None
  921. return self.getexif()._get_merged_dict()
  922. def getexif(self) -> Image.Exif:
  923. if "exif" not in self.info:
  924. self.load()
  925. return super().getexif()
  926. # --------------------------------------------------------------------
  927. # PNG writer
  928. _OUTMODES = {
  929. # supported PIL modes, and corresponding rawmode, bit depth and color type
  930. "1": ("1", b"\x01", b"\x00"),
  931. "L;1": ("L;1", b"\x01", b"\x00"),
  932. "L;2": ("L;2", b"\x02", b"\x00"),
  933. "L;4": ("L;4", b"\x04", b"\x00"),
  934. "L": ("L", b"\x08", b"\x00"),
  935. "LA": ("LA", b"\x08", b"\x04"),
  936. "I": ("I;16B", b"\x10", b"\x00"),
  937. "I;16": ("I;16B", b"\x10", b"\x00"),
  938. "I;16B": ("I;16B", b"\x10", b"\x00"),
  939. "P;1": ("P;1", b"\x01", b"\x03"),
  940. "P;2": ("P;2", b"\x02", b"\x03"),
  941. "P;4": ("P;4", b"\x04", b"\x03"),
  942. "P": ("P", b"\x08", b"\x03"),
  943. "RGB": ("RGB", b"\x08", b"\x02"),
  944. "RGBA": ("RGBA", b"\x08", b"\x06"),
  945. }
  946. def putchunk(fp: IO[bytes], cid: bytes, *data: bytes) -> None:
  947. """Write a PNG chunk (including CRC field)"""
  948. byte_data = b"".join(data)
  949. fp.write(o32(len(byte_data)) + cid)
  950. fp.write(byte_data)
  951. crc = _crc32(byte_data, _crc32(cid))
  952. fp.write(o32(crc))
  953. class _idat:
  954. # wrap output from the encoder in IDAT chunks
  955. def __init__(self, fp: IO[bytes], chunk: Callable[..., None]) -> None:
  956. self.fp = fp
  957. self.chunk = chunk
  958. def write(self, data: bytes) -> None:
  959. self.chunk(self.fp, b"IDAT", data)
  960. class _fdat:
  961. # wrap encoder output in fdAT chunks
  962. def __init__(self, fp: IO[bytes], chunk: Callable[..., None], seq_num: int) -> None:
  963. self.fp = fp
  964. self.chunk = chunk
  965. self.seq_num = seq_num
  966. def write(self, data: bytes) -> None:
  967. self.chunk(self.fp, b"fdAT", o32(self.seq_num), data)
  968. self.seq_num += 1
  969. class _Frame(NamedTuple):
  970. im: Image.Image
  971. bbox: tuple[int, int, int, int] | None
  972. encoderinfo: dict[str, Any]
  973. def _write_multiple_frames(
  974. im: Image.Image,
  975. fp: IO[bytes],
  976. chunk: Callable[..., None],
  977. mode: str,
  978. rawmode: str,
  979. default_image: Image.Image | None,
  980. append_images: list[Image.Image],
  981. ) -> Image.Image | None:
  982. duration = im.encoderinfo.get("duration")
  983. loop = im.encoderinfo.get("loop", im.info.get("loop", 0))
  984. disposal = im.encoderinfo.get("disposal", im.info.get("disposal", Disposal.OP_NONE))
  985. blend = im.encoderinfo.get("blend", im.info.get("blend", Blend.OP_SOURCE))
  986. if default_image:
  987. chain = itertools.chain(append_images)
  988. else:
  989. chain = itertools.chain([im], append_images)
  990. im_frames: list[_Frame] = []
  991. frame_count = 0
  992. for im_seq in chain:
  993. for im_frame in ImageSequence.Iterator(im_seq):
  994. if im_frame.mode == mode:
  995. im_frame = im_frame.copy()
  996. else:
  997. im_frame = im_frame.convert(mode)
  998. encoderinfo = im.encoderinfo.copy()
  999. if isinstance(duration, (list, tuple)):
  1000. encoderinfo["duration"] = duration[frame_count]
  1001. elif duration is None and "duration" in im_frame.info:
  1002. encoderinfo["duration"] = im_frame.info["duration"]
  1003. if isinstance(disposal, (list, tuple)):
  1004. encoderinfo["disposal"] = disposal[frame_count]
  1005. if isinstance(blend, (list, tuple)):
  1006. encoderinfo["blend"] = blend[frame_count]
  1007. frame_count += 1
  1008. if im_frames:
  1009. previous = im_frames[-1]
  1010. prev_disposal = previous.encoderinfo.get("disposal")
  1011. prev_blend = previous.encoderinfo.get("blend")
  1012. if prev_disposal == Disposal.OP_PREVIOUS and len(im_frames) < 2:
  1013. prev_disposal = Disposal.OP_BACKGROUND
  1014. if prev_disposal == Disposal.OP_BACKGROUND:
  1015. base_im = previous.im.copy()
  1016. dispose = Image.core.fill("RGBA", im.size, (0, 0, 0, 0))
  1017. bbox = previous.bbox
  1018. if bbox:
  1019. dispose = dispose.crop(bbox)
  1020. else:
  1021. bbox = (0, 0) + im.size
  1022. base_im.paste(dispose, bbox)
  1023. elif prev_disposal == Disposal.OP_PREVIOUS:
  1024. base_im = im_frames[-2].im
  1025. else:
  1026. base_im = previous.im
  1027. delta = ImageChops.subtract_modulo(
  1028. im_frame.convert("RGBA"), base_im.convert("RGBA")
  1029. )
  1030. bbox = delta.getbbox(alpha_only=False)
  1031. if (
  1032. not bbox
  1033. and prev_disposal == encoderinfo.get("disposal")
  1034. and prev_blend == encoderinfo.get("blend")
  1035. and "duration" in encoderinfo
  1036. ):
  1037. previous.encoderinfo["duration"] += encoderinfo["duration"]
  1038. continue
  1039. else:
  1040. bbox = None
  1041. im_frames.append(_Frame(im_frame, bbox, encoderinfo))
  1042. if len(im_frames) == 1 and not default_image:
  1043. return im_frames[0].im
  1044. # animation control
  1045. chunk(
  1046. fp,
  1047. b"acTL",
  1048. o32(len(im_frames)), # 0: num_frames
  1049. o32(loop), # 4: num_plays
  1050. )
  1051. # default image IDAT (if it exists)
  1052. if default_image:
  1053. if im.mode != mode:
  1054. im = im.convert(mode)
  1055. ImageFile._save(
  1056. im,
  1057. cast(IO[bytes], _idat(fp, chunk)),
  1058. [ImageFile._Tile("zip", (0, 0) + im.size, 0, rawmode)],
  1059. )
  1060. seq_num = 0
  1061. for frame, frame_data in enumerate(im_frames):
  1062. im_frame = frame_data.im
  1063. if not frame_data.bbox:
  1064. bbox = (0, 0) + im_frame.size
  1065. else:
  1066. bbox = frame_data.bbox
  1067. im_frame = im_frame.crop(bbox)
  1068. size = im_frame.size
  1069. encoderinfo = frame_data.encoderinfo
  1070. frame_duration = int(round(encoderinfo.get("duration", 0)))
  1071. frame_disposal = encoderinfo.get("disposal", disposal)
  1072. frame_blend = encoderinfo.get("blend", blend)
  1073. # frame control
  1074. chunk(
  1075. fp,
  1076. b"fcTL",
  1077. o32(seq_num), # sequence_number
  1078. o32(size[0]), # width
  1079. o32(size[1]), # height
  1080. o32(bbox[0]), # x_offset
  1081. o32(bbox[1]), # y_offset
  1082. o16(frame_duration), # delay_numerator
  1083. o16(1000), # delay_denominator
  1084. o8(frame_disposal), # dispose_op
  1085. o8(frame_blend), # blend_op
  1086. )
  1087. seq_num += 1
  1088. # frame data
  1089. if frame == 0 and not default_image:
  1090. # first frame must be in IDAT chunks for backwards compatibility
  1091. ImageFile._save(
  1092. im_frame,
  1093. cast(IO[bytes], _idat(fp, chunk)),
  1094. [ImageFile._Tile("zip", (0, 0) + im_frame.size, 0, rawmode)],
  1095. )
  1096. else:
  1097. fdat_chunks = _fdat(fp, chunk, seq_num)
  1098. ImageFile._save(
  1099. im_frame,
  1100. cast(IO[bytes], fdat_chunks),
  1101. [ImageFile._Tile("zip", (0, 0) + im_frame.size, 0, rawmode)],
  1102. )
  1103. seq_num = fdat_chunks.seq_num
  1104. return None
  1105. def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  1106. _save(im, fp, filename, save_all=True)
  1107. def _save(
  1108. im: Image.Image,
  1109. fp: IO[bytes],
  1110. filename: str | bytes,
  1111. chunk: Callable[..., None] = putchunk,
  1112. save_all: bool = False,
  1113. ) -> None:
  1114. # save an image to disk (called by the save method)
  1115. if save_all:
  1116. default_image = im.encoderinfo.get(
  1117. "default_image", im.info.get("default_image")
  1118. )
  1119. modes = set()
  1120. sizes = set()
  1121. append_images = im.encoderinfo.get("append_images", [])
  1122. for im_seq in itertools.chain([im], append_images):
  1123. for im_frame in ImageSequence.Iterator(im_seq):
  1124. modes.add(im_frame.mode)
  1125. sizes.add(im_frame.size)
  1126. for mode in ("RGBA", "RGB", "P"):
  1127. if mode in modes:
  1128. break
  1129. else:
  1130. mode = modes.pop()
  1131. size = tuple(max(frame_size[i] for frame_size in sizes) for i in range(2))
  1132. else:
  1133. size = im.size
  1134. mode = im.mode
  1135. outmode = mode
  1136. if mode == "P":
  1137. #
  1138. # attempt to minimize storage requirements for palette images
  1139. if "bits" in im.encoderinfo:
  1140. # number of bits specified by user
  1141. colors = min(1 << im.encoderinfo["bits"], 256)
  1142. else:
  1143. # check palette contents
  1144. if im.palette:
  1145. colors = max(min(len(im.palette.getdata()[1]) // 3, 256), 1)
  1146. else:
  1147. colors = 256
  1148. if colors <= 16:
  1149. if colors <= 2:
  1150. bits = 1
  1151. elif colors <= 4:
  1152. bits = 2
  1153. else:
  1154. bits = 4
  1155. outmode += f";{bits}"
  1156. # encoder options
  1157. im.encoderconfig = (
  1158. im.encoderinfo.get("optimize", False),
  1159. im.encoderinfo.get("compress_level", -1),
  1160. im.encoderinfo.get("compress_type", -1),
  1161. im.encoderinfo.get("dictionary", b""),
  1162. )
  1163. # get the corresponding PNG mode
  1164. try:
  1165. rawmode, bit_depth, color_type = _OUTMODES[outmode]
  1166. except KeyError as e:
  1167. msg = f"cannot write mode {mode} as PNG"
  1168. raise OSError(msg) from e
  1169. if outmode == "I":
  1170. deprecate("Saving I mode images as PNG", 13, stacklevel=4)
  1171. #
  1172. # write minimal PNG file
  1173. fp.write(_MAGIC)
  1174. chunk(
  1175. fp,
  1176. b"IHDR",
  1177. o32(size[0]), # 0: size
  1178. o32(size[1]),
  1179. bit_depth,
  1180. color_type,
  1181. b"\0", # 10: compression
  1182. b"\0", # 11: filter category
  1183. b"\0", # 12: interlace flag
  1184. )
  1185. chunks = [b"cHRM", b"cICP", b"gAMA", b"sBIT", b"sRGB", b"tIME"]
  1186. icc = im.encoderinfo.get("icc_profile", im.info.get("icc_profile"))
  1187. if icc:
  1188. # ICC profile
  1189. # according to PNG spec, the iCCP chunk contains:
  1190. # Profile name 1-79 bytes (character string)
  1191. # Null separator 1 byte (null character)
  1192. # Compression method 1 byte (0)
  1193. # Compressed profile n bytes (zlib with deflate compression)
  1194. name = b"ICC Profile"
  1195. data = name + b"\0\0" + zlib.compress(icc)
  1196. chunk(fp, b"iCCP", data)
  1197. # You must either have sRGB or iCCP.
  1198. # Disallow sRGB chunks when an iCCP-chunk has been emitted.
  1199. chunks.remove(b"sRGB")
  1200. info = im.encoderinfo.get("pnginfo")
  1201. if info:
  1202. chunks_multiple_allowed = [b"sPLT", b"iTXt", b"tEXt", b"zTXt"]
  1203. for info_chunk in info.chunks:
  1204. cid, data = info_chunk[:2]
  1205. if cid in chunks:
  1206. chunks.remove(cid)
  1207. chunk(fp, cid, data)
  1208. elif cid in chunks_multiple_allowed:
  1209. chunk(fp, cid, data)
  1210. elif cid[1:2].islower():
  1211. # Private chunk
  1212. after_idat = len(info_chunk) == 3 and info_chunk[2]
  1213. if not after_idat:
  1214. chunk(fp, cid, data)
  1215. if im.mode == "P":
  1216. palette_byte_number = colors * 3
  1217. palette_bytes = im.im.getpalette("RGB")[:palette_byte_number]
  1218. while len(palette_bytes) < palette_byte_number:
  1219. palette_bytes += b"\0"
  1220. chunk(fp, b"PLTE", palette_bytes)
  1221. transparency = im.encoderinfo.get("transparency", im.info.get("transparency", None))
  1222. if transparency or transparency == 0:
  1223. if im.mode == "P":
  1224. # limit to actual palette size
  1225. alpha_bytes = colors
  1226. if isinstance(transparency, bytes):
  1227. chunk(fp, b"tRNS", transparency[:alpha_bytes])
  1228. else:
  1229. transparency = max(0, min(255, transparency))
  1230. alpha = b"\xff" * transparency + b"\0"
  1231. chunk(fp, b"tRNS", alpha[:alpha_bytes])
  1232. elif im.mode in ("1", "L", "I", "I;16"):
  1233. transparency = max(0, min(65535, transparency))
  1234. chunk(fp, b"tRNS", o16(transparency))
  1235. elif im.mode == "RGB":
  1236. red, green, blue = transparency
  1237. chunk(fp, b"tRNS", o16(red) + o16(green) + o16(blue))
  1238. else:
  1239. if "transparency" in im.encoderinfo:
  1240. # don't bother with transparency if it's an RGBA
  1241. # and it's in the info dict. It's probably just stale.
  1242. msg = "cannot use transparency for this mode"
  1243. raise OSError(msg)
  1244. else:
  1245. if im.mode == "P" and im.im.getpalettemode() == "RGBA":
  1246. alpha = im.im.getpalette("RGBA", "A")
  1247. alpha_bytes = colors
  1248. chunk(fp, b"tRNS", alpha[:alpha_bytes])
  1249. dpi = im.encoderinfo.get("dpi")
  1250. if dpi:
  1251. chunk(
  1252. fp,
  1253. b"pHYs",
  1254. o32(int(dpi[0] / 0.0254 + 0.5)),
  1255. o32(int(dpi[1] / 0.0254 + 0.5)),
  1256. b"\x01",
  1257. )
  1258. if info:
  1259. chunks = [b"bKGD", b"hIST"]
  1260. for info_chunk in info.chunks:
  1261. cid, data = info_chunk[:2]
  1262. if cid in chunks:
  1263. chunks.remove(cid)
  1264. chunk(fp, cid, data)
  1265. exif = im.encoderinfo.get("exif")
  1266. if exif:
  1267. if isinstance(exif, Image.Exif):
  1268. exif = exif.tobytes(8)
  1269. if exif.startswith(b"Exif\x00\x00"):
  1270. exif = exif[6:]
  1271. chunk(fp, b"eXIf", exif)
  1272. single_im: Image.Image | None = im
  1273. if save_all:
  1274. single_im = _write_multiple_frames(
  1275. im, fp, chunk, mode, rawmode, default_image, append_images
  1276. )
  1277. if single_im:
  1278. ImageFile._save(
  1279. single_im,
  1280. cast(IO[bytes], _idat(fp, chunk)),
  1281. [ImageFile._Tile("zip", (0, 0) + single_im.size, 0, rawmode)],
  1282. )
  1283. if info:
  1284. for info_chunk in info.chunks:
  1285. cid, data = info_chunk[:2]
  1286. if cid[1:2].islower():
  1287. # Private chunk
  1288. after_idat = len(info_chunk) == 3 and info_chunk[2]
  1289. if after_idat:
  1290. chunk(fp, cid, data)
  1291. chunk(fp, b"IEND", b"")
  1292. if hasattr(fp, "flush"):
  1293. fp.flush()
  1294. # --------------------------------------------------------------------
  1295. # PNG chunk converter
  1296. def getchunks(im: Image.Image, **params: Any) -> list[tuple[bytes, bytes, bytes]]:
  1297. """Return a list of PNG chunks representing this image."""
  1298. from io import BytesIO
  1299. chunks = []
  1300. def append(fp: IO[bytes], cid: bytes, *data: bytes) -> None:
  1301. byte_data = b"".join(data)
  1302. crc = o32(_crc32(byte_data, _crc32(cid)))
  1303. chunks.append((cid, byte_data, crc))
  1304. fp = BytesIO()
  1305. try:
  1306. im.encoderinfo = params
  1307. _save(im, fp, "", append)
  1308. finally:
  1309. del im.encoderinfo
  1310. return chunks
  1311. # --------------------------------------------------------------------
  1312. # Registry
  1313. Image.register_open(PngImageFile.format, PngImageFile, _accept)
  1314. Image.register_save(PngImageFile.format, _save)
  1315. Image.register_save_all(PngImageFile.format, _save_all)
  1316. Image.register_extensions(PngImageFile.format, [".png", ".apng"])
  1317. Image.register_mime(PngImageFile.format, "image/png")