WebPImagePlugin.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. from __future__ import annotations
  2. from io import BytesIO
  3. from . import Image, ImageFile
  4. try:
  5. from . import _webp
  6. SUPPORTED = True
  7. except ImportError:
  8. SUPPORTED = False
  9. TYPE_CHECKING = False
  10. if TYPE_CHECKING:
  11. from typing import IO, Any
  12. _VP8_MODES_BY_IDENTIFIER = {
  13. b"VP8 ": "RGB",
  14. b"VP8X": "RGBA",
  15. b"VP8L": "RGBA", # lossless
  16. }
  17. def _accept(prefix: bytes) -> bool | str:
  18. is_riff_file_format = prefix.startswith(b"RIFF")
  19. is_webp_file = prefix[8:12] == b"WEBP"
  20. is_valid_vp8_mode = prefix[12:16] in _VP8_MODES_BY_IDENTIFIER
  21. if is_riff_file_format and is_webp_file and is_valid_vp8_mode:
  22. if not SUPPORTED:
  23. return (
  24. "image file could not be identified because WEBP support not installed"
  25. )
  26. return True
  27. return False
  28. class WebPImageFile(ImageFile.ImageFile):
  29. format = "WEBP"
  30. format_description = "WebP image"
  31. __loaded = 0
  32. __logical_frame = 0
  33. def _open(self) -> None:
  34. # Use the newer AnimDecoder API to parse the (possibly) animated file,
  35. # and access muxed chunks like ICC/EXIF/XMP.
  36. self._decoder = _webp.WebPAnimDecoder(self.fp.read())
  37. # Get info from decoder
  38. self._size, loop_count, bgcolor, frame_count, mode = self._decoder.get_info()
  39. self.info["loop"] = loop_count
  40. bg_a, bg_r, bg_g, bg_b = (
  41. (bgcolor >> 24) & 0xFF,
  42. (bgcolor >> 16) & 0xFF,
  43. (bgcolor >> 8) & 0xFF,
  44. bgcolor & 0xFF,
  45. )
  46. self.info["background"] = (bg_r, bg_g, bg_b, bg_a)
  47. self.n_frames = frame_count
  48. self.is_animated = self.n_frames > 1
  49. self._mode = "RGB" if mode == "RGBX" else mode
  50. self.rawmode = mode
  51. # Attempt to read ICC / EXIF / XMP chunks from file
  52. icc_profile = self._decoder.get_chunk("ICCP")
  53. exif = self._decoder.get_chunk("EXIF")
  54. xmp = self._decoder.get_chunk("XMP ")
  55. if icc_profile:
  56. self.info["icc_profile"] = icc_profile
  57. if exif:
  58. self.info["exif"] = exif
  59. if xmp:
  60. self.info["xmp"] = xmp
  61. # Initialize seek state
  62. self._reset(reset=False)
  63. def _getexif(self) -> dict[int, Any] | None:
  64. if "exif" not in self.info:
  65. return None
  66. return self.getexif()._get_merged_dict()
  67. def seek(self, frame: int) -> None:
  68. if not self._seek_check(frame):
  69. return
  70. # Set logical frame to requested position
  71. self.__logical_frame = frame
  72. def _reset(self, reset: bool = True) -> None:
  73. if reset:
  74. self._decoder.reset()
  75. self.__physical_frame = 0
  76. self.__loaded = -1
  77. self.__timestamp = 0
  78. def _get_next(self) -> tuple[bytes, int, int]:
  79. # Get next frame
  80. ret = self._decoder.get_next()
  81. self.__physical_frame += 1
  82. # Check if an error occurred
  83. if ret is None:
  84. self._reset() # Reset just to be safe
  85. self.seek(0)
  86. msg = "failed to decode next frame in WebP file"
  87. raise EOFError(msg)
  88. # Compute duration
  89. data, timestamp = ret
  90. duration = timestamp - self.__timestamp
  91. self.__timestamp = timestamp
  92. # libwebp gives frame end, adjust to start of frame
  93. timestamp -= duration
  94. return data, timestamp, duration
  95. def _seek(self, frame: int) -> None:
  96. if self.__physical_frame == frame:
  97. return # Nothing to do
  98. if frame < self.__physical_frame:
  99. self._reset() # Rewind to beginning
  100. while self.__physical_frame < frame:
  101. self._get_next() # Advance to the requested frame
  102. def load(self) -> Image.core.PixelAccess | None:
  103. if self.__loaded != self.__logical_frame:
  104. self._seek(self.__logical_frame)
  105. # We need to load the image data for this frame
  106. data, timestamp, duration = self._get_next()
  107. self.info["timestamp"] = timestamp
  108. self.info["duration"] = duration
  109. self.__loaded = self.__logical_frame
  110. # Set tile
  111. if self.fp and self._exclusive_fp:
  112. self.fp.close()
  113. self.fp = BytesIO(data)
  114. self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 0, self.rawmode)]
  115. return super().load()
  116. def load_seek(self, pos: int) -> None:
  117. pass
  118. def tell(self) -> int:
  119. return self.__logical_frame
  120. def _convert_frame(im: Image.Image) -> Image.Image:
  121. # Make sure image mode is supported
  122. if im.mode not in ("RGBX", "RGBA", "RGB"):
  123. im = im.convert("RGBA" if im.has_transparency_data else "RGB")
  124. return im
  125. def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  126. encoderinfo = im.encoderinfo.copy()
  127. append_images = list(encoderinfo.get("append_images", []))
  128. # If total frame count is 1, then save using the legacy API, which
  129. # will preserve non-alpha modes
  130. total = 0
  131. for ims in [im] + append_images:
  132. total += getattr(ims, "n_frames", 1)
  133. if total == 1:
  134. _save(im, fp, filename)
  135. return
  136. background: int | tuple[int, ...] = (0, 0, 0, 0)
  137. if "background" in encoderinfo:
  138. background = encoderinfo["background"]
  139. elif "background" in im.info:
  140. background = im.info["background"]
  141. if isinstance(background, int):
  142. # GifImagePlugin stores a global color table index in
  143. # info["background"]. So it must be converted to an RGBA value
  144. palette = im.getpalette()
  145. if palette:
  146. r, g, b = palette[background * 3 : (background + 1) * 3]
  147. background = (r, g, b, 255)
  148. else:
  149. background = (background, background, background, 255)
  150. duration = im.encoderinfo.get("duration", im.info.get("duration", 0))
  151. loop = im.encoderinfo.get("loop", 0)
  152. minimize_size = im.encoderinfo.get("minimize_size", False)
  153. kmin = im.encoderinfo.get("kmin", None)
  154. kmax = im.encoderinfo.get("kmax", None)
  155. allow_mixed = im.encoderinfo.get("allow_mixed", False)
  156. verbose = False
  157. lossless = im.encoderinfo.get("lossless", False)
  158. quality = im.encoderinfo.get("quality", 80)
  159. alpha_quality = im.encoderinfo.get("alpha_quality", 100)
  160. method = im.encoderinfo.get("method", 0)
  161. icc_profile = im.encoderinfo.get("icc_profile") or ""
  162. exif = im.encoderinfo.get("exif", "")
  163. if isinstance(exif, Image.Exif):
  164. exif = exif.tobytes()
  165. xmp = im.encoderinfo.get("xmp", "")
  166. if allow_mixed:
  167. lossless = False
  168. # Sensible keyframe defaults are from gif2webp.c script
  169. if kmin is None:
  170. kmin = 9 if lossless else 3
  171. if kmax is None:
  172. kmax = 17 if lossless else 5
  173. # Validate background color
  174. if (
  175. not isinstance(background, (list, tuple))
  176. or len(background) != 4
  177. or not all(0 <= v < 256 for v in background)
  178. ):
  179. msg = f"Background color is not an RGBA tuple clamped to (0-255): {background}"
  180. raise OSError(msg)
  181. # Convert to packed uint
  182. bg_r, bg_g, bg_b, bg_a = background
  183. background = (bg_a << 24) | (bg_r << 16) | (bg_g << 8) | (bg_b << 0)
  184. # Setup the WebP animation encoder
  185. enc = _webp.WebPAnimEncoder(
  186. im.size,
  187. background,
  188. loop,
  189. minimize_size,
  190. kmin,
  191. kmax,
  192. allow_mixed,
  193. verbose,
  194. )
  195. # Add each frame
  196. frame_idx = 0
  197. timestamp = 0
  198. cur_idx = im.tell()
  199. try:
  200. for ims in [im] + append_images:
  201. # Get number of frames in this image
  202. nfr = getattr(ims, "n_frames", 1)
  203. for idx in range(nfr):
  204. ims.seek(idx)
  205. frame = _convert_frame(ims)
  206. # Append the frame to the animation encoder
  207. enc.add(
  208. frame.getim(),
  209. round(timestamp),
  210. lossless,
  211. quality,
  212. alpha_quality,
  213. method,
  214. )
  215. # Update timestamp and frame index
  216. if isinstance(duration, (list, tuple)):
  217. timestamp += duration[frame_idx]
  218. else:
  219. timestamp += duration
  220. frame_idx += 1
  221. finally:
  222. im.seek(cur_idx)
  223. # Force encoder to flush frames
  224. enc.add(None, round(timestamp), lossless, quality, alpha_quality, 0)
  225. # Get the final output from the encoder
  226. data = enc.assemble(icc_profile, exif, xmp)
  227. if data is None:
  228. msg = "cannot write file as WebP (encoder returned None)"
  229. raise OSError(msg)
  230. fp.write(data)
  231. def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  232. lossless = im.encoderinfo.get("lossless", False)
  233. quality = im.encoderinfo.get("quality", 80)
  234. alpha_quality = im.encoderinfo.get("alpha_quality", 100)
  235. icc_profile = im.encoderinfo.get("icc_profile") or ""
  236. exif = im.encoderinfo.get("exif", b"")
  237. if isinstance(exif, Image.Exif):
  238. exif = exif.tobytes()
  239. if exif.startswith(b"Exif\x00\x00"):
  240. exif = exif[6:]
  241. xmp = im.encoderinfo.get("xmp", "")
  242. method = im.encoderinfo.get("method", 4)
  243. exact = 1 if im.encoderinfo.get("exact") else 0
  244. im = _convert_frame(im)
  245. data = _webp.WebPEncode(
  246. im.getim(),
  247. lossless,
  248. float(quality),
  249. float(alpha_quality),
  250. icc_profile,
  251. method,
  252. exact,
  253. exif,
  254. xmp,
  255. )
  256. if data is None:
  257. msg = "cannot write file as WebP (encoder returned None)"
  258. raise OSError(msg)
  259. fp.write(data)
  260. Image.register_open(WebPImageFile.format, WebPImageFile, _accept)
  261. if SUPPORTED:
  262. Image.register_save(WebPImageFile.format, _save)
  263. Image.register_save_all(WebPImageFile.format, _save_all)
  264. Image.register_extension(WebPImageFile.format, ".webp")
  265. Image.register_mime(WebPImageFile.format, "image/webp")