Pillow/PIL/WebPImagePlugin.py

81 lines
2.0 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",
2014-08-26 17:47:10 +04:00
b"VP8L": "RGBA", # lossless
}
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"
def _open(self):
2014-08-26 17:47:10 +04:00
data, width, height, self.mode, icc_profile, exif = \
_webp.WebPDecode(self.fp.read())
if icc_profile:
self.info["icc_profile"] = icc_profile
if exif:
self.info["exif"] = exif
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)]
def _getexif(self):
from PIL.JpegImagePlugin import _getexif
return _getexif(self)
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)
lossless = im.encoderinfo.get("lossless", False)
2013-03-12 18:30:59 +04:00
quality = im.encoderinfo.get("quality", 80)
icc_profile = im.encoderinfo.get("icc_profile", "")
exif = im.encoderinfo.get("exif", "")
2013-05-16 03:56:59 +04:00
data = _webp.WebPEncode(
im.tobytes(),
im.size[0],
im.size[1],
lossless,
float(quality),
im.mode,
icc_profile,
exif
)
if data is None:
raise IOError("cannot write file as WEBP (encoder returned None)")
2013-03-12 18:30:59 +04:00
fp.write(data)
Image.register_open(WebPImageFile.format, WebPImageFile, _accept)
Image.register_save(WebPImageFile.format, _save)
2013-03-12 18:30:59 +04:00
Image.register_extension(WebPImageFile.format, ".webp")
Image.register_mime(WebPImageFile.format, "image/webp")