WebPImagePlugin.py 11 KB

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