WebPImagePlugin.py 11 KB

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