Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

WebPImagePlugin.py 11KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. __loaded = 0
  29. __logical_frame = 0
  30. def _open(self):
  31. if not _webp.HAVE_WEBPANIM:
  32. # Legacy mode
  33. data, width, height, self.mode, icc_profile, exif = _webp.WebPDecode(
  34. self.fp.read()
  35. )
  36. if icc_profile:
  37. self.info["icc_profile"] = icc_profile
  38. if exif:
  39. self.info["exif"] = exif
  40. self._size = width, height
  41. self.fp = BytesIO(data)
  42. self.tile = [("raw", (0, 0) + self.size, 0, self.mode)]
  43. self.n_frames = 1
  44. self.is_animated = False
  45. return
  46. # Use the newer AnimDecoder API to parse the (possibly) animated file,
  47. # and access muxed chunks like ICC/EXIF/XMP.
  48. self._decoder = _webp.WebPAnimDecoder(self.fp.read())
  49. # Get info from decoder
  50. width, height, loop_count, bgcolor, frame_count, mode = self._decoder.get_info()
  51. self._size = width, height
  52. self.info["loop"] = loop_count
  53. bg_a, bg_r, bg_g, bg_b = (
  54. (bgcolor >> 24) & 0xFF,
  55. (bgcolor >> 16) & 0xFF,
  56. (bgcolor >> 8) & 0xFF,
  57. bgcolor & 0xFF,
  58. )
  59. self.info["background"] = (bg_r, bg_g, bg_b, bg_a)
  60. self.n_frames = frame_count
  61. self.is_animated = self.n_frames > 1
  62. self.mode = "RGB" if mode == "RGBX" else mode
  63. self.rawmode = mode
  64. self.tile = []
  65. # Attempt to read ICC / EXIF / XMP chunks from file
  66. icc_profile = self._decoder.get_chunk("ICCP")
  67. exif = self._decoder.get_chunk("EXIF")
  68. xmp = self._decoder.get_chunk("XMP ")
  69. if icc_profile:
  70. self.info["icc_profile"] = icc_profile
  71. if exif:
  72. self.info["exif"] = exif
  73. if xmp:
  74. self.info["xmp"] = xmp
  75. # Initialize seek state
  76. self._reset(reset=False)
  77. def _getexif(self):
  78. if "exif" not in self.info:
  79. return None
  80. return self.getexif()._get_merged_dict()
  81. def getxmp(self):
  82. """
  83. Returns a dictionary containing the XMP tags.
  84. Requires defusedxml to be installed.
  85. :returns: XMP tags in a dictionary.
  86. """
  87. return self._getxmp(self.info["xmp"]) if "xmp" in self.info else {}
  88. def seek(self, frame):
  89. if not self._seek_check(frame):
  90. return
  91. # Set logical frame to requested position
  92. self.__logical_frame = frame
  93. def _reset(self, reset=True):
  94. if reset:
  95. self._decoder.reset()
  96. self.__physical_frame = 0
  97. self.__loaded = -1
  98. self.__timestamp = 0
  99. def _get_next(self):
  100. # Get next frame
  101. ret = self._decoder.get_next()
  102. self.__physical_frame += 1
  103. # Check if an error occurred
  104. if ret is None:
  105. self._reset() # Reset just to be safe
  106. self.seek(0)
  107. msg = "failed to decode next frame in WebP file"
  108. raise EOFError(msg)
  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().load()
  138. def tell(self):
  139. if not _webp.HAVE_WEBPANIM:
  140. return super().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, 255)
  165. else:
  166. background = (background, background, background, 255)
  167. duration = im.encoderinfo.get("duration", im.info.get("duration", 0))
  168. loop = im.encoderinfo.get("loop", 0)
  169. minimize_size = im.encoderinfo.get("minimize_size", False)
  170. kmin = im.encoderinfo.get("kmin", None)
  171. kmax = im.encoderinfo.get("kmax", None)
  172. allow_mixed = im.encoderinfo.get("allow_mixed", False)
  173. verbose = False
  174. lossless = im.encoderinfo.get("lossless", False)
  175. quality = im.encoderinfo.get("quality", 80)
  176. method = im.encoderinfo.get("method", 0)
  177. icc_profile = im.encoderinfo.get("icc_profile") or ""
  178. exif = im.encoderinfo.get("exif", "")
  179. if isinstance(exif, Image.Exif):
  180. exif = exif.tobytes()
  181. xmp = im.encoderinfo.get("xmp", "")
  182. if allow_mixed:
  183. lossless = False
  184. # Sensible keyframe defaults are from gif2webp.c script
  185. if kmin is None:
  186. kmin = 9 if lossless else 3
  187. if kmax is None:
  188. kmax = 17 if lossless else 5
  189. # Validate background color
  190. if (
  191. not isinstance(background, (list, tuple))
  192. or len(background) != 4
  193. or not all(0 <= v < 256 for v in background)
  194. ):
  195. msg = f"Background color is not an RGBA tuple clamped to (0-255): {background}"
  196. raise OSError(msg)
  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. round(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, round(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. msg = "cannot write file as WebP (encoder returned None)"
  262. raise OSError(msg)
  263. fp.write(data)
  264. def _save(im, fp, filename):
  265. lossless = im.encoderinfo.get("lossless", False)
  266. quality = im.encoderinfo.get("quality", 80)
  267. icc_profile = im.encoderinfo.get("icc_profile") or ""
  268. exif = im.encoderinfo.get("exif", b"")
  269. if isinstance(exif, Image.Exif):
  270. exif = exif.tobytes()
  271. if exif.startswith(b"Exif\x00\x00"):
  272. exif = exif[6:]
  273. xmp = im.encoderinfo.get("xmp", "")
  274. method = im.encoderinfo.get("method", 4)
  275. exact = 1 if im.encoderinfo.get("exact") else 0
  276. if im.mode not in _VALID_WEBP_LEGACY_MODES:
  277. alpha = (
  278. "A" in im.mode
  279. or "a" in im.mode
  280. or (im.mode == "P" and "transparency" in im.info)
  281. )
  282. im = im.convert("RGBA" if alpha else "RGB")
  283. data = _webp.WebPEncode(
  284. im.tobytes(),
  285. im.size[0],
  286. im.size[1],
  287. lossless,
  288. float(quality),
  289. im.mode,
  290. icc_profile,
  291. method,
  292. exact,
  293. exif,
  294. xmp,
  295. )
  296. if data is None:
  297. msg = "cannot write file as WebP (encoder returned None)"
  298. raise OSError(msg)
  299. fp.write(data)
  300. Image.register_open(WebPImageFile.format, WebPImageFile, _accept)
  301. if SUPPORTED:
  302. Image.register_save(WebPImageFile.format, _save)
  303. if _webp.HAVE_WEBPANIM:
  304. Image.register_save_all(WebPImageFile.format, _save_all)
  305. Image.register_extension(WebPImageFile.format, ".webp")
  306. Image.register_mime(WebPImageFile.format, "image/webp")