PngImagePlugin.py 53 KB

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