Pillow/PIL/WebPImagePlugin.py

60 lines
1.4 KiB
Python
Raw Normal View History

2013-03-14 06:03:38 +04:00
from PIL import Image
from PIL import ImageFile
2013-03-14 06:42:21 +04:00
from io import BytesIO
2013-04-09 08:53:59 +04:00
from PIL import _webp
2013-03-12 18:30:59 +04:00
_VALID_WEBP_MODES = {
"RGB": True,
"RGBA": True,
}
_VP8_MODES_BY_IDENTIFIER = {
b"VP8 ": "RGB",
b"VP8X": "RGBA",
}
2013-03-12 18:30:59 +04:00
def _accept(prefix):
is_riff_file_format = prefix[:4] == b"RIFF"
is_webp_file = prefix[8:12] == b"WEBP"
is_valid_vp8_mode = prefix[12:16] in _VP8_MODES_BY_IDENTIFIER
return is_riff_file_format and is_webp_file and is_valid_vp8_mode
2013-03-12 18:30:59 +04:00
class WebPImageFile(ImageFile.ImageFile):
format = "WEBP"
format_description = "WebP image"
2013-05-14 07:50:10 +04:00
def _open(self):
data, width, height, self.mode = _webp.WebPDecode(self.fp.read())
2013-03-12 18:30:59 +04:00
self.size = width, height
2013-03-14 06:42:21 +04:00
self.fp = BytesIO(data)
2013-05-14 07:50:10 +04:00
self.tile = [("raw", (0, 0) + self.size, 0, self.mode)]
2013-03-12 18:30:59 +04:00
def _save(im, fp, filename):
image_mode = im.mode
if im.mode not in _VALID_WEBP_MODES:
raise IOError("cannot write mode %s as WEBP" % image_mode)
2013-03-12 18:30:59 +04:00
quality = im.encoderinfo.get("quality", 80)
2013-05-16 03:56:59 +04:00
data = _webp.WebPEncode(
im.tobytes(),
im.size[0],
im.size[1],
float(quality),
2013-05-16 03:56:59 +04:00
im.mode
)
2013-03-12 18:30:59 +04:00
fp.write(data)
2013-03-12 18:30:59 +04:00
Image.register_open("WEBP", WebPImageFile, _accept)
Image.register_save("WEBP", _save)
Image.register_extension("WEBP", ".webp")
Image.register_mime("WEBP", "image/webp")