GifImagePlugin.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # GIF file handling
  6. #
  7. # History:
  8. # 1995-09-01 fl Created
  9. # 1996-12-14 fl Added interlace support
  10. # 1996-12-30 fl Added animation support
  11. # 1997-01-05 fl Added write support, fixed local colour map bug
  12. # 1997-02-23 fl Make sure to load raster data in getdata()
  13. # 1997-07-05 fl Support external decoder (0.4)
  14. # 1998-07-09 fl Handle all modes when saving (0.5)
  15. # 1998-07-15 fl Renamed offset attribute to avoid name clash
  16. # 2001-04-16 fl Added rewind support (seek to frame 0) (0.6)
  17. # 2001-04-17 fl Added palette optimization (0.7)
  18. # 2002-06-06 fl Added transparency support for save (0.8)
  19. # 2004-02-24 fl Disable interlacing for small images
  20. #
  21. # Copyright (c) 1997-2004 by Secret Labs AB
  22. # Copyright (c) 1995-2004 by Fredrik Lundh
  23. #
  24. # See the README file for information on usage and redistribution.
  25. #
  26. from __future__ import annotations
  27. __lazy_modules__ = {
  28. "PIL._binary",
  29. "PIL._util",
  30. "itertools",
  31. "math",
  32. "subprocess",
  33. }
  34. import itertools
  35. import math
  36. from enum import IntEnum
  37. from functools import cached_property
  38. from typing import NamedTuple, cast
  39. from . import (
  40. Image,
  41. ImageChops,
  42. ImageFile,
  43. ImagePalette,
  44. ImageSequence,
  45. )
  46. from ._binary import i16le as i16
  47. from ._binary import o8
  48. from ._binary import o16le as o16
  49. from ._util import DeferredError
  50. TYPE_CHECKING = False
  51. if TYPE_CHECKING:
  52. from typing import IO, Any, Literal
  53. from . import _imaging
  54. from ._typing import Buffer
  55. class LoadingStrategy(IntEnum):
  56. """.. versionadded:: 9.1.0"""
  57. RGB_AFTER_FIRST = 0
  58. RGB_AFTER_DIFFERENT_PALETTE_ONLY = 1
  59. RGB_ALWAYS = 2
  60. #: .. versionadded:: 9.1.0
  61. LOADING_STRATEGY = LoadingStrategy.RGB_AFTER_FIRST
  62. # --------------------------------------------------------------------
  63. # Identify/read GIF files
  64. def _accept(prefix: bytes) -> bool:
  65. return prefix.startswith((b"GIF87a", b"GIF89a"))
  66. ##
  67. # Image plugin for GIF images. This plugin supports both GIF87 and
  68. # GIF89 images.
  69. class GifImageFile(ImageFile.ImageFile):
  70. format = "GIF"
  71. format_description = "Compuserve GIF"
  72. _close_exclusive_fp_after_loading = False
  73. global_palette = None
  74. def data(self) -> bytes | None:
  75. assert self.fp is not None
  76. s = self.fp.read(1)
  77. if s and s[0]:
  78. return self.fp.read(s[0])
  79. return None
  80. def _is_palette_needed(self, p: bytes) -> bool:
  81. for i in range(0, len(p), 3):
  82. if not (i // 3 == p[i] == p[i + 1] == p[i + 2]):
  83. return True
  84. return False
  85. def _open(self) -> None:
  86. # Screen
  87. assert self.fp is not None
  88. s = self.fp.read(13)
  89. if not _accept(s):
  90. msg = "not a GIF file"
  91. raise SyntaxError(msg)
  92. self.info["version"] = s[:6]
  93. self._size = i16(s, 6), i16(s, 8)
  94. flags = s[10]
  95. bits = (flags & 7) + 1
  96. if flags & 128:
  97. # get global palette
  98. self.info["background"] = s[11]
  99. # check if palette contains colour indices
  100. p = self.fp.read(3 << bits)
  101. if self._is_palette_needed(p):
  102. palette = ImagePalette.raw("RGB", p)
  103. self.global_palette = self.palette = palette
  104. self._fp = self.fp # FIXME: hack
  105. self.__rewind = self.fp.tell()
  106. self._n_frames: int | None = None
  107. self._seek(0) # get ready to read first frame
  108. @property
  109. def n_frames(self) -> int:
  110. if self._n_frames is None:
  111. current = self.tell()
  112. try:
  113. while True:
  114. self._seek(self.tell() + 1, False)
  115. except EOFError:
  116. self._n_frames = self.tell() + 1
  117. self.seek(current)
  118. return self._n_frames
  119. @cached_property
  120. def is_animated(self) -> bool:
  121. if self._n_frames is not None:
  122. return self._n_frames != 1
  123. current = self.tell()
  124. if current:
  125. return True
  126. try:
  127. self._seek(1, False)
  128. is_animated = True
  129. except EOFError:
  130. is_animated = False
  131. self.seek(current)
  132. return is_animated
  133. def seek(self, frame: int) -> None:
  134. if not self._seek_check(frame):
  135. return
  136. if frame < self.__frame:
  137. self._im = None
  138. self._seek(0)
  139. last_frame = self.__frame
  140. try:
  141. for f in range(self.__frame + 1, frame + 1):
  142. self._seek(f)
  143. except EOFError as e:
  144. self.seek(last_frame)
  145. msg = "no more images in GIF file"
  146. raise EOFError(msg) from e
  147. def _seek(self, frame: int, update_image: bool = True) -> None:
  148. if isinstance(self._fp, DeferredError):
  149. raise self._fp.ex
  150. if frame == 0:
  151. # rewind
  152. self.__offset = 0
  153. self.dispose: _imaging.ImagingCore | None = None
  154. self.__frame = -1
  155. self._fp.seek(self.__rewind)
  156. self.disposal_method = 0
  157. if "comment" in self.info:
  158. del self.info["comment"]
  159. else:
  160. # ensure that the previous frame was loaded
  161. if self.tile and update_image:
  162. self.load()
  163. if frame != self.__frame + 1:
  164. msg = f"cannot seek to frame {frame}"
  165. raise ValueError(msg)
  166. self.fp = self._fp
  167. if self.__offset:
  168. # backup to last frame
  169. self.fp.seek(self.__offset)
  170. while self.data():
  171. pass
  172. self.__offset = 0
  173. s = self.fp.read(1)
  174. if not s or s == b";":
  175. msg = "no more images in GIF file"
  176. raise EOFError(msg)
  177. palette: ImagePalette.ImagePalette | Literal[False] | None = None
  178. info: dict[str, Any] = {}
  179. comment_blocks: list[bytes] = []
  180. frame_transparency = None
  181. interlace = None
  182. frame_dispose_extent = None
  183. while True:
  184. if not s:
  185. s = self.fp.read(1)
  186. if not s or s == b";":
  187. break
  188. elif s == b"!":
  189. #
  190. # extensions
  191. #
  192. s = self.fp.read(1)
  193. block = self.data()
  194. if s[0] == 249 and block is not None:
  195. #
  196. # graphic control extension
  197. #
  198. flags = block[0]
  199. if flags & 1:
  200. frame_transparency = block[3]
  201. info["duration"] = i16(block, 1) * 10
  202. # disposal method - find the value of bits 4 - 6
  203. dispose_bits = 0b00011100 & flags
  204. dispose_bits = dispose_bits >> 2
  205. if dispose_bits:
  206. # only set the dispose if it is not
  207. # unspecified. I'm not sure if this is
  208. # correct, but it seems to prevent the last
  209. # frame from looking odd for some animations
  210. self.disposal_method = dispose_bits
  211. elif s[0] == 254:
  212. #
  213. # comment extension
  214. #
  215. if block and comment_blocks:
  216. # If multiple comment blocks in frame, separate with \n
  217. comment_blocks.append(b"\n")
  218. while block:
  219. comment_blocks.append(block)
  220. block = self.data()
  221. s = b""
  222. continue
  223. elif s[0] == 255 and frame == 0 and block is not None:
  224. #
  225. # application extension
  226. #
  227. info["extension"] = block, self.fp.tell()
  228. if block.startswith(b"NETSCAPE2.0"):
  229. block = self.data()
  230. if block and len(block) >= 3 and block[0] == 1:
  231. self.info["loop"] = i16(block, 1)
  232. while self.data():
  233. pass
  234. elif s == b",":
  235. #
  236. # local image
  237. #
  238. s = self.fp.read(9)
  239. # extent
  240. x0, y0 = i16(s, 0), i16(s, 2)
  241. x1, y1 = x0 + i16(s, 4), y0 + i16(s, 6)
  242. if (x1 > self.size[0] or y1 > self.size[1]) and update_image:
  243. size = max(x1, self.size[0]), max(y1, self.size[1])
  244. Image._decompression_bomb_check(size)
  245. self._size = size
  246. frame_dispose_extent = x0, y0, x1, y1
  247. flags = s[8]
  248. interlace = (flags & 64) != 0
  249. if flags & 128:
  250. bits = (flags & 7) + 1
  251. p = self.fp.read(3 << bits)
  252. if self._is_palette_needed(p):
  253. palette = ImagePalette.raw("RGB", p)
  254. else:
  255. palette = False
  256. # image data
  257. bits = self.fp.read(1)[0]
  258. self.__offset = self.fp.tell()
  259. break
  260. s = b""
  261. if interlace is None:
  262. msg = "image not found in GIF frame"
  263. raise EOFError(msg)
  264. self.__frame = frame
  265. if not update_image:
  266. return
  267. self.tile = []
  268. if self.dispose:
  269. self.im.paste(self.dispose, self.dispose_extent)
  270. self._frame_palette = palette if palette is not None else self.global_palette
  271. self._frame_transparency = frame_transparency
  272. if frame == 0:
  273. if self._frame_palette:
  274. if LOADING_STRATEGY == LoadingStrategy.RGB_ALWAYS:
  275. self._mode = "RGBA" if frame_transparency is not None else "RGB"
  276. else:
  277. self._mode = "P"
  278. else:
  279. self._mode = "L"
  280. if palette:
  281. self.palette = palette
  282. elif self.global_palette:
  283. from copy import copy
  284. self.palette = copy(self.global_palette)
  285. else:
  286. self.palette = None
  287. else:
  288. if self.mode == "P":
  289. if (
  290. LOADING_STRATEGY != LoadingStrategy.RGB_AFTER_DIFFERENT_PALETTE_ONLY
  291. or palette
  292. ):
  293. if "transparency" in self.info:
  294. self.im.putpalettealpha(self.info["transparency"], 0)
  295. self.im = self.im.convert("RGBA", Image.Dither.FLOYDSTEINBERG)
  296. self._mode = "RGBA"
  297. del self.info["transparency"]
  298. else:
  299. self._mode = "RGB"
  300. self.im = self.im.convert("RGB", Image.Dither.FLOYDSTEINBERG)
  301. def _rgb(color: int) -> tuple[int, int, int]:
  302. if self._frame_palette:
  303. if color * 3 + 3 > len(self._frame_palette.palette):
  304. color = 0
  305. return cast(
  306. "tuple[int, int, int]",
  307. tuple(self._frame_palette.palette[color * 3 : color * 3 + 3]),
  308. )
  309. else:
  310. return (color, color, color)
  311. self.dispose = None
  312. self.dispose_extent: tuple[int, int, int, int] | None = frame_dispose_extent
  313. if self.dispose_extent and self.disposal_method >= 2:
  314. try:
  315. if self.disposal_method == 2:
  316. # replace with background colour
  317. # only dispose the extent in this frame
  318. x0, y0, x1, y1 = self.dispose_extent
  319. dispose_size = (x1 - x0, y1 - y0)
  320. Image._decompression_bomb_check(dispose_size)
  321. # by convention, attempt to use transparency first
  322. dispose_mode = "P"
  323. color = self.info.get("transparency", frame_transparency)
  324. if color is not None:
  325. if self.mode in ("RGB", "RGBA"):
  326. dispose_mode = "RGBA"
  327. color = _rgb(color) + (0,)
  328. else:
  329. color = self.info.get("background", 0)
  330. if self.mode in ("RGB", "RGBA"):
  331. dispose_mode = "RGB"
  332. color = _rgb(color)
  333. self.dispose = Image.core.fill(dispose_mode, dispose_size, color)
  334. else:
  335. # replace with previous contents
  336. if self._im is not None:
  337. # only dispose the extent in this frame
  338. self.dispose = self._crop(self.im, self.dispose_extent)
  339. elif frame_transparency is not None:
  340. x0, y0, x1, y1 = self.dispose_extent
  341. dispose_size = (x1 - x0, y1 - y0)
  342. Image._decompression_bomb_check(dispose_size)
  343. dispose_mode = "P"
  344. color = frame_transparency
  345. if self.mode in ("RGB", "RGBA"):
  346. dispose_mode = "RGBA"
  347. color = _rgb(frame_transparency) + (0,)
  348. self.dispose = Image.core.fill(
  349. dispose_mode, dispose_size, color
  350. )
  351. except AttributeError:
  352. pass
  353. if interlace is not None:
  354. transparency = -1
  355. if frame_transparency is not None:
  356. if frame == 0:
  357. if LOADING_STRATEGY != LoadingStrategy.RGB_ALWAYS:
  358. self.info["transparency"] = frame_transparency
  359. elif self.mode not in ("RGB", "RGBA"):
  360. transparency = frame_transparency
  361. self.tile = [
  362. ImageFile._Tile(
  363. "gif",
  364. (x0, y0, x1, y1),
  365. self.__offset,
  366. (bits, interlace, transparency),
  367. )
  368. ]
  369. if comment_blocks:
  370. self.info["comment"] = b"".join(comment_blocks)
  371. for k in ["duration", "extension"]:
  372. if k in info:
  373. self.info[k] = info[k]
  374. elif k in self.info:
  375. del self.info[k]
  376. def load_prepare(self) -> None:
  377. temp_mode = "P" if self._frame_palette else "L"
  378. self._prev_im = None
  379. if self.__frame == 0:
  380. if self._frame_transparency is not None:
  381. self.im = Image.core.fill(
  382. temp_mode, self.size, self._frame_transparency
  383. )
  384. elif self.mode in ("RGB", "RGBA"):
  385. self._prev_im = self.im
  386. if self._frame_palette:
  387. self.im = Image.core.fill("P", self.size, self._frame_transparency or 0)
  388. self.im.putpalette("RGB", *self._frame_palette.getdata())
  389. else:
  390. self._im = None
  391. if not self._prev_im and self._im is not None and self.size != self.im.size:
  392. expanded_im = Image.core.fill(self.im.mode, self.size)
  393. if self._frame_palette:
  394. expanded_im.putpalette("RGB", *self._frame_palette.getdata())
  395. expanded_im.paste(self.im, (0, 0, *self.im.size))
  396. self.im = expanded_im
  397. self._mode = temp_mode
  398. self._frame_palette = None
  399. super().load_prepare()
  400. def load_end(self) -> None:
  401. if self.__frame == 0:
  402. if self.mode == "P" and LOADING_STRATEGY == LoadingStrategy.RGB_ALWAYS:
  403. if self._frame_transparency is not None:
  404. self.im.putpalettealpha(self._frame_transparency, 0)
  405. self._mode = "RGBA"
  406. else:
  407. self._mode = "RGB"
  408. self.im = self.im.convert(self.mode, Image.Dither.FLOYDSTEINBERG)
  409. return
  410. if not self._prev_im:
  411. return
  412. if self.size != self._prev_im.size:
  413. if self._frame_transparency is not None:
  414. expanded_im = Image.core.fill("RGBA", self.size)
  415. else:
  416. expanded_im = Image.core.fill("P", self.size)
  417. expanded_im.putpalette("RGB", "RGB", self.im.getpalette())
  418. expanded_im = expanded_im.convert("RGB")
  419. expanded_im.paste(self._prev_im, (0, 0, *self._prev_im.size))
  420. self._prev_im = expanded_im
  421. assert self._prev_im is not None
  422. if self._frame_transparency is not None:
  423. if self.mode == "L":
  424. frame_im = self.im.convert_transparent("LA", self._frame_transparency)
  425. else:
  426. self.im.putpalettealpha(self._frame_transparency, 0)
  427. frame_im = self.im.convert("RGBA")
  428. else:
  429. frame_im = self.im.convert("RGB")
  430. assert self.dispose_extent is not None
  431. frame_im = self._crop(frame_im, self.dispose_extent)
  432. self.im = self._prev_im
  433. self._mode = self.im.mode
  434. if frame_im.mode in ("LA", "RGBA"):
  435. self.im.paste(frame_im, self.dispose_extent, frame_im)
  436. else:
  437. self.im.paste(frame_im, self.dispose_extent)
  438. def tell(self) -> int:
  439. return self.__frame
  440. # --------------------------------------------------------------------
  441. # Write GIF files
  442. RAWMODE = {"1": "L", "L": "L", "P": "P"}
  443. def _normalize_mode(im: Image.Image) -> Image.Image:
  444. """
  445. Takes an image (or frame), returns an image in a mode that is appropriate
  446. for saving in a Gif.
  447. It may return the original image, or it may return an image converted to
  448. palette or 'L' mode.
  449. :param im: Image object
  450. :returns: Image object
  451. """
  452. if im.mode in RAWMODE:
  453. im.load()
  454. return im
  455. if Image.getmodebase(im.mode) == "RGB":
  456. im = im.convert("P", palette=Image.Palette.ADAPTIVE)
  457. assert im.palette is not None
  458. if im.palette.mode == "RGBA":
  459. for rgba in im.palette.colors:
  460. if rgba[3] == 0:
  461. im.info["transparency"] = im.palette.colors[rgba]
  462. break
  463. return im
  464. return im.convert("L")
  465. _Palette = bytes | bytearray | list[int] | ImagePalette.ImagePalette
  466. def _normalize_palette(
  467. im: Image.Image, palette: _Palette | None, info: dict[str, Any]
  468. ) -> Image.Image:
  469. """
  470. Normalizes the palette for image.
  471. - Sets the palette to the incoming palette, if provided.
  472. - Ensures that there's a palette for L mode images
  473. - Optimizes the palette if necessary/desired.
  474. :param im: Image object
  475. :param palette: bytes object containing the source palette, or ....
  476. :param info: encoderinfo
  477. :returns: Image object
  478. """
  479. source_palette = None
  480. if palette:
  481. # a bytes palette
  482. if isinstance(palette, (bytes, bytearray, list)):
  483. source_palette = bytearray(palette[:768])
  484. if isinstance(palette, ImagePalette.ImagePalette):
  485. source_palette = bytearray(palette.palette)
  486. if im.mode == "P":
  487. if not source_palette:
  488. im_palette = im.getpalette(None)
  489. assert im_palette is not None
  490. source_palette = bytearray(im_palette)
  491. else: # L-mode
  492. if not source_palette:
  493. source_palette = bytearray(i // 3 for i in range(768))
  494. im.palette = ImagePalette.ImagePalette("RGB", palette=source_palette)
  495. assert source_palette is not None
  496. if palette:
  497. used_palette_colors: list[int | None] = []
  498. assert im.palette is not None
  499. for i in range(0, len(source_palette), 3):
  500. source_color = tuple(source_palette[i : i + 3])
  501. index = im.palette.colors.get(source_color)
  502. if index in used_palette_colors:
  503. index = None
  504. used_palette_colors.append(index)
  505. for i, index in enumerate(used_palette_colors):
  506. if index is None:
  507. for j in range(len(used_palette_colors)):
  508. if j not in used_palette_colors:
  509. used_palette_colors[i] = j
  510. break
  511. dest_map: list[int] = []
  512. for index in used_palette_colors:
  513. assert index is not None
  514. dest_map.append(index)
  515. im = im.remap_palette(dest_map)
  516. else:
  517. optimized_palette_colors = _get_optimize(im, info)
  518. if optimized_palette_colors is not None:
  519. im = im.remap_palette(optimized_palette_colors, source_palette)
  520. if "transparency" in info:
  521. try:
  522. info["transparency"] = optimized_palette_colors.index(
  523. info["transparency"]
  524. )
  525. except ValueError:
  526. del info["transparency"]
  527. return im
  528. assert im.palette is not None
  529. im.palette.palette = source_palette
  530. return im
  531. def _write_single_frame(
  532. im: Image.Image,
  533. fp: IO[bytes],
  534. palette: _Palette | None,
  535. ) -> None:
  536. im_out = _normalize_mode(im)
  537. for k, v in im_out.info.items():
  538. if isinstance(k, str):
  539. im.encoderinfo.setdefault(k, v)
  540. im_out = _normalize_palette(im_out, palette, im.encoderinfo)
  541. for s in _get_global_header(im_out, im.encoderinfo):
  542. fp.write(s)
  543. # local image header
  544. flags = 0
  545. if get_interlace(im):
  546. flags = flags | 64
  547. _write_local_header(fp, im, (0, 0), flags)
  548. im_out.encoderconfig = (8, get_interlace(im))
  549. ImageFile._save(
  550. im_out, fp, [ImageFile._Tile("gif", (0, 0, *im.size), 0, RAWMODE[im_out.mode])]
  551. )
  552. fp.write(b"\0") # end of image data
  553. def _getbbox(
  554. base_im: Image.Image, im_frame: Image.Image
  555. ) -> tuple[Image.Image, tuple[int, int, int, int] | None]:
  556. palette_bytes = [
  557. bytes(im.palette.palette) if im.palette else b"" for im in (base_im, im_frame)
  558. ]
  559. if palette_bytes[0] != palette_bytes[1]:
  560. im_frame = im_frame.convert("RGBA")
  561. base_im = base_im.convert("RGBA")
  562. delta = ImageChops.subtract_modulo(im_frame, base_im)
  563. return delta, delta.getbbox(alpha_only=False)
  564. class _Frame(NamedTuple):
  565. im: Image.Image
  566. bbox: tuple[int, int, int, int] | None
  567. encoderinfo: dict[str, Any]
  568. def _write_multiple_frames(
  569. im: Image.Image, fp: IO[bytes], palette: _Palette | None
  570. ) -> bool:
  571. duration = im.encoderinfo.get("duration")
  572. disposal = im.encoderinfo.get("disposal", im.info.get("disposal"))
  573. im_frames: list[_Frame] = []
  574. previous_im: Image.Image | None = None
  575. frame_count = 0
  576. background_im = None
  577. for imSequence in itertools.chain([im], im.encoderinfo.get("append_images", [])):
  578. for im_frame in ImageSequence.Iterator(imSequence):
  579. # a copy is required here since seek can still mutate the image
  580. im_frame = _normalize_mode(im_frame.copy())
  581. if frame_count == 0:
  582. for k, v in im_frame.info.items():
  583. if k == "transparency":
  584. continue
  585. if isinstance(k, str):
  586. im.encoderinfo.setdefault(k, v)
  587. encoderinfo = im.encoderinfo.copy()
  588. if "transparency" in im_frame.info:
  589. encoderinfo.setdefault("transparency", im_frame.info["transparency"])
  590. im_frame = _normalize_palette(im_frame, palette, encoderinfo)
  591. if isinstance(duration, (list, tuple)):
  592. encoderinfo["duration"] = duration[frame_count]
  593. elif duration is None and "duration" in im_frame.info:
  594. encoderinfo["duration"] = im_frame.info["duration"]
  595. if isinstance(disposal, (list, tuple)):
  596. encoderinfo["disposal"] = disposal[frame_count]
  597. frame_count += 1
  598. diff_frame = None
  599. if im_frames and previous_im:
  600. # delta frame
  601. delta, bbox = _getbbox(previous_im, im_frame)
  602. if not bbox:
  603. # This frame is identical to the previous frame
  604. if encoderinfo.get("duration"):
  605. im_frames[-1].encoderinfo["duration"] = (
  606. im_frames[-1].encoderinfo.get("duration", 0)
  607. + encoderinfo["duration"]
  608. )
  609. continue
  610. if im_frames[-1].encoderinfo.get("disposal") == 2:
  611. # To appear correctly in viewers using a convention,
  612. # only consider transparency, and not background color
  613. color = im.encoderinfo.get(
  614. "transparency", im.info.get("transparency")
  615. )
  616. if color is not None:
  617. if background_im is None:
  618. background = _get_background(im_frame, color)
  619. background_im = Image.new("P", im_frame.size, background)
  620. first_palette = im_frames[0].im.palette
  621. assert first_palette is not None
  622. background_im.putpalette(first_palette, first_palette.mode)
  623. bbox = _getbbox(background_im, im_frame)[1]
  624. else:
  625. bbox = (0, 0, *im_frame.size)
  626. elif encoderinfo.get("optimize") and im_frame.mode != "1":
  627. if "transparency" not in encoderinfo:
  628. assert im_frame.palette is not None
  629. try:
  630. encoderinfo["transparency"] = (
  631. im_frame.palette._new_color_index(im_frame)
  632. )
  633. except ValueError:
  634. pass
  635. if "transparency" in encoderinfo:
  636. # When the delta is zero, fill the image with transparency
  637. if delta.mode == "RGBA":
  638. # Each pixel is unchanged only if all four bands are zero
  639. r, g, b, a = delta.split()
  640. delta = ImageChops.lighter(
  641. ImageChops.lighter(r, g),
  642. ImageChops.lighter(b, a),
  643. )
  644. # Map zero pixels (palette indices, for "P")
  645. # to a "1" mask without consulting the palette.
  646. unchanged = delta.point([255, *(0,) * 255], "1")
  647. diff_frame = im_frame.copy()
  648. diff_frame.paste(encoderinfo["transparency"], mask=unchanged)
  649. else:
  650. bbox = None
  651. previous_im = im_frame
  652. im_frames.append(_Frame(diff_frame or im_frame, bbox, encoderinfo))
  653. if len(im_frames) == 1:
  654. if "duration" in im_frames[0].encoderinfo:
  655. # Since multiple frames will not be written, use the combined duration
  656. im.encoderinfo["duration"] = im_frames[0].encoderinfo["duration"]
  657. return False
  658. for frame_data in im_frames:
  659. im_frame = frame_data.im
  660. if not frame_data.bbox:
  661. # global header
  662. for s in _get_global_header(im_frame, frame_data.encoderinfo):
  663. fp.write(s)
  664. offset = (0, 0)
  665. else:
  666. # compress difference
  667. if not palette:
  668. frame_data.encoderinfo["include_color_table"] = True
  669. if frame_data.bbox != (0, 0, *im_frame.size):
  670. im_frame = im_frame.crop(frame_data.bbox)
  671. offset = frame_data.bbox[:2]
  672. _write_frame_data(fp, im_frame, offset, frame_data.encoderinfo)
  673. return True
  674. def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  675. _save(im, fp, filename, save_all=True)
  676. def _save(
  677. im: Image.Image, fp: IO[bytes], filename: str | bytes, save_all: bool = False
  678. ) -> None:
  679. # header
  680. if "palette" in im.encoderinfo or "palette" in im.info:
  681. palette = im.encoderinfo.get("palette", im.info.get("palette"))
  682. else:
  683. palette = None
  684. im.encoderinfo.setdefault("optimize", True)
  685. if not save_all or not _write_multiple_frames(im, fp, palette):
  686. _write_single_frame(im, fp, palette)
  687. fp.write(b";") # end of file
  688. if hasattr(fp, "flush"):
  689. fp.flush()
  690. def get_interlace(im: Image.Image) -> int:
  691. interlace = im.encoderinfo.get("interlace", 1)
  692. # workaround for @PIL153
  693. if min(im.size) < 16:
  694. interlace = 0
  695. return interlace
  696. def _write_local_header(
  697. fp: IO[bytes], im: Image.Image, offset: tuple[int, int], flags: int
  698. ) -> None:
  699. try:
  700. transparency = im.encoderinfo["transparency"]
  701. except KeyError:
  702. transparency = None
  703. if "duration" in im.encoderinfo:
  704. duration = int(im.encoderinfo["duration"] / 10)
  705. else:
  706. duration = 0
  707. disposal = int(im.encoderinfo.get("disposal", 0))
  708. if transparency is not None or duration != 0 or disposal:
  709. packed_flag = 1 if transparency is not None else 0
  710. packed_flag |= disposal << 2
  711. fp.write(
  712. b"!"
  713. + o8(249) # extension intro
  714. + o8(4) # length
  715. + o8(packed_flag) # packed fields
  716. + o16(duration) # duration
  717. + o8(transparency or 0) # transparency index
  718. + o8(0)
  719. )
  720. include_color_table = im.encoderinfo.get("include_color_table")
  721. if include_color_table:
  722. palette_bytes = _get_palette_bytes(im)
  723. color_table_size = _get_color_table_size(palette_bytes)
  724. if color_table_size:
  725. flags = flags | 128 # local color table flag
  726. flags = flags | color_table_size
  727. fp.write(
  728. b","
  729. + o16(offset[0]) # offset
  730. + o16(offset[1])
  731. + o16(im.size[0]) # size
  732. + o16(im.size[1])
  733. + o8(flags) # flags
  734. )
  735. if include_color_table and color_table_size:
  736. fp.write(_get_header_palette(palette_bytes))
  737. fp.write(o8(8)) # bits
  738. # Force optimization so that we can test performance against
  739. # cases where it took lots of memory and time previously.
  740. _FORCE_OPTIMIZE = False
  741. def _get_optimize(im: Image.Image, info: dict[str, Any]) -> list[int] | None:
  742. """
  743. Palette optimization is a potentially expensive operation.
  744. This function determines if the palette should be optimized using
  745. some heuristics, then returns the list of palette entries in use.
  746. :param im: Image object
  747. :param info: encoderinfo
  748. :returns: list of indexes of palette entries in use, or None
  749. """
  750. if (
  751. im.mode in ("P", "L")
  752. and info
  753. and info.get("optimize")
  754. and im.width != 0
  755. and im.height != 0
  756. ):
  757. # Potentially expensive operation.
  758. # The palette saves 3 bytes per color not used, but palette
  759. # lengths are restricted to 3*(2**N) bytes. Max saving would
  760. # be 768 -> 6 bytes if we went all the way down to 2 colors.
  761. # * If we're over 128 colors, we can't save any space.
  762. # * If there aren't any holes, it's not worth collapsing.
  763. # * If we have a 'large' image, the palette is in the noise.
  764. # create the new palette if not every color is used
  765. optimise = _FORCE_OPTIMIZE or im.mode == "L"
  766. if optimise or im.width * im.height < 512 * 512:
  767. # check which colors are used
  768. used_palette_colors = []
  769. for i, count in enumerate(im.histogram()):
  770. if count:
  771. used_palette_colors.append(i)
  772. if optimise or max(used_palette_colors) >= len(used_palette_colors):
  773. return used_palette_colors
  774. assert im.palette is not None
  775. num_palette_colors = len(im.palette.palette) // Image.getmodebands(
  776. im.palette.mode
  777. )
  778. current_palette_size = 1 << (num_palette_colors - 1).bit_length()
  779. if (
  780. # check that the palette would become smaller when saved
  781. len(used_palette_colors) <= current_palette_size // 2
  782. # check that the palette is not already the smallest possible size
  783. and current_palette_size > 2
  784. ):
  785. return used_palette_colors
  786. return None
  787. def _get_color_table_size(palette_bytes: bytes) -> int:
  788. # calculate the palette size for the header
  789. if not palette_bytes:
  790. return 0
  791. elif len(palette_bytes) < 9:
  792. return 1
  793. else:
  794. return math.ceil(math.log(len(palette_bytes) // 3, 2)) - 1
  795. def _get_header_palette(palette_bytes: bytes) -> bytes:
  796. """
  797. Returns the palette, null padded to the next power of 2 (*3) bytes
  798. suitable for direct inclusion in the GIF header
  799. :param palette_bytes: Unpadded palette bytes, in RGBRGB form
  800. :returns: Null padded palette
  801. """
  802. color_table_size = _get_color_table_size(palette_bytes)
  803. # add the missing amount of bytes
  804. # the palette has to be 2<<n in size
  805. actual_target_size_diff = (2 << color_table_size) - len(palette_bytes) // 3
  806. if actual_target_size_diff > 0:
  807. palette_bytes += o8(0) * 3 * actual_target_size_diff
  808. return palette_bytes
  809. def _get_palette_bytes(im: Image.Image) -> bytes:
  810. """
  811. Gets the palette for inclusion in the gif header
  812. :param im: Image object
  813. :returns: Bytes, len<=768 suitable for inclusion in gif header
  814. """
  815. if not im.palette:
  816. return b""
  817. palette = bytes(im.palette.palette)
  818. if im.palette.mode == "RGBA":
  819. palette = b"".join(palette[i * 4 : i * 4 + 3] for i in range(len(palette) // 3))
  820. return palette
  821. def _get_background(
  822. im: Image.Image,
  823. info_background: int | tuple[int, int, int] | tuple[int, int, int, int] | None,
  824. ) -> int:
  825. background = 0
  826. if info_background:
  827. if isinstance(info_background, tuple):
  828. # WebPImagePlugin stores an RGBA value in info["background"]
  829. # So it must be converted to the same format as GifImagePlugin's
  830. # info["background"] - a global color table index
  831. assert im.palette is not None
  832. try:
  833. background = im.palette.getcolor(info_background, im)
  834. except ValueError as e:
  835. if str(e) not in (
  836. # If all 256 colors are in use,
  837. # then there is no need for the background color
  838. "cannot allocate more than 256 colors",
  839. # Ignore non-opaque WebP background
  840. "cannot add non-opaque RGBA color to RGB palette",
  841. ):
  842. raise
  843. else:
  844. background = info_background
  845. return background
  846. def _get_global_header(im: Image.Image, info: dict[str, Any]) -> list[bytes]:
  847. """Return a list of strings representing a GIF header"""
  848. # Header Block
  849. # https://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp
  850. version = b"87a"
  851. if im.info.get("version") == b"89a" or (
  852. info
  853. and (
  854. "transparency" in info
  855. or info.get("loop") is not None
  856. or info.get("duration")
  857. or info.get("comment")
  858. )
  859. ):
  860. version = b"89a"
  861. background = _get_background(im, info.get("background"))
  862. palette_bytes = _get_palette_bytes(im)
  863. color_table_size = _get_color_table_size(palette_bytes)
  864. header = [
  865. b"GIF" # signature
  866. + version # version
  867. + o16(im.size[0]) # canvas width
  868. + o16(im.size[1]), # canvas height
  869. # Logical Screen Descriptor
  870. # size of global color table + global color table flag
  871. o8(color_table_size + 128), # packed fields
  872. # background + reserved/aspect
  873. o8(background) + o8(0),
  874. # Global Color Table
  875. _get_header_palette(palette_bytes),
  876. ]
  877. if info.get("loop") is not None:
  878. header.append(
  879. b"!"
  880. + o8(255) # extension intro
  881. + o8(11)
  882. + b"NETSCAPE2.0"
  883. + o8(3)
  884. + o8(1)
  885. + o16(info["loop"]) # number of loops
  886. + o8(0)
  887. )
  888. if info.get("comment"):
  889. header.append(b"!" + o8(254)) # extension intro
  890. comment = info["comment"]
  891. if isinstance(comment, str):
  892. comment = comment.encode()
  893. for i in range(0, len(comment), 255):
  894. subblock = comment[i : i + 255]
  895. header.append(o8(len(subblock)) + subblock)
  896. header.append(o8(0))
  897. return header
  898. def _write_frame_data(
  899. fp: IO[bytes],
  900. im_frame: Image.Image,
  901. offset: tuple[int, int],
  902. params: dict[str, Any],
  903. ) -> None:
  904. try:
  905. im_frame.encoderinfo = params
  906. # local image header
  907. _write_local_header(fp, im_frame, offset, 0)
  908. ImageFile._save(
  909. im_frame,
  910. fp,
  911. [ImageFile._Tile("gif", (0, 0, *im_frame.size), 0, RAWMODE[im_frame.mode])],
  912. )
  913. fp.write(b"\0") # end of image data
  914. finally:
  915. del im_frame.encoderinfo
  916. # --------------------------------------------------------------------
  917. # Legacy GIF utilities
  918. def getheader(
  919. im: Image.Image, palette: _Palette | None = None, info: dict[str, Any] | None = None
  920. ) -> tuple[list[bytes], list[int] | None]:
  921. """
  922. Legacy Method to get Gif data from image.
  923. Warning:: May modify image data.
  924. :param im: Image object
  925. :param palette: bytes object containing the source palette, or ....
  926. :param info: encoderinfo
  927. :returns: tuple of(list of header items, optimized palette)
  928. """
  929. if info is None:
  930. info = {}
  931. used_palette_colors = _get_optimize(im, info)
  932. if "background" not in info and "background" in im.info:
  933. info["background"] = im.info["background"]
  934. im_mod = _normalize_palette(im, palette, info)
  935. im.palette = im_mod.palette
  936. im.im = im_mod.im
  937. header = _get_global_header(im, info)
  938. return header, used_palette_colors
  939. def getdata(
  940. im: Image.Image, offset: tuple[int, int] = (0, 0), **params: Any
  941. ) -> list[bytes]:
  942. """
  943. Legacy Method
  944. Return a list of strings representing this image.
  945. The first string is a local image header, the rest contains
  946. encoded image data.
  947. To specify duration, add the time in milliseconds,
  948. e.g. ``getdata(im_frame, duration=1000)``
  949. :param im: Image object
  950. :param offset: Tuple of (x, y) pixels. Defaults to (0, 0)
  951. :param \\**params: e.g. duration or other encoder info parameters
  952. :returns: List of bytes containing GIF encoded frame data
  953. """
  954. from io import BytesIO
  955. class Collector(BytesIO):
  956. data = []
  957. def write(self, data: Buffer) -> int:
  958. self.data.append(data)
  959. return len(data)
  960. im.load() # make sure raster data is available
  961. fp = Collector()
  962. _write_frame_data(fp, im, offset, params)
  963. return fp.data
  964. # --------------------------------------------------------------------
  965. # Registry
  966. Image.register_open(GifImageFile.format, GifImageFile, _accept)
  967. Image.register_save(GifImageFile.format, _save)
  968. Image.register_save_all(GifImageFile.format, _save_all)
  969. Image.register_extension(GifImageFile.format, ".gif")
  970. Image.register_mime(GifImageFile.format, "image/gif")