checking raw image length, cleanup and DRY

This commit is contained in:
wiredfool 2013-05-15 17:04:17 -07:00
parent 11a0fb5f76
commit 89b6820530
2 changed files with 11 additions and 21 deletions

View File

@ -4,24 +4,11 @@ from io import BytesIO
import _webp
_VALID_WEBP_ENCODERS_BY_MODE = {
"RGB": _webp.WebPEncode,
"RGBA": _webp.WebPEncode,
_VALID_WEBP_MODES = {
"RGB": True,
"RGBA": True,
}
_VALID_WEBP_DECODERS_BY_MODE = {
"RGB": _webp.WebPDecode,
"RGBA": _webp.WebPDecode,
}
_STRIDE_MULTIPLIERS_BY_MODE = {
"RGB": 3,
"RGBA": 4,
}
_VP8_MODES_BY_IDENTIFIER = {
b"VP8 ": "RGB",
b"VP8X": "RGBA",
@ -50,7 +37,7 @@ class WebPImageFile(ImageFile.ImageFile):
def _save(im, fp, filename):
image_mode = im.mode
if im.mode not in _VALID_WEBP_ENCODERS_BY_MODE:
if im.mode not in _VALID_WEBP_MODES:
raise IOError("cannot write mode %s as WEBP" % image_mode)
quality = im.encoderinfo.get("quality", 80)

11
_webp.c
View File

@ -7,7 +7,6 @@
PyObject* WebPEncode_wrapper(PyObject* self, PyObject* args)
{
PyBytesObject *rgb_string;
int width;
int height;
float quality_factor;
@ -17,15 +16,19 @@ PyObject* WebPEncode_wrapper(PyObject* self, PyObject* args)
Py_ssize_t size;
size_t ret_size;
if (!PyArg_ParseTuple(args, "Siifs", &rgb_string, &width, &height, &quality_factor, &mode)) {
if (!PyArg_ParseTuple(args, "s#iifs",(char**)&rgb, &size, &width, &height, &quality_factor, &mode)) {
Py_RETURN_NONE;
}
PyBytes_AsStringAndSize((PyObject *) rgb_string, (char**)&rgb, &size);
if (strcmp(mode, "RGBA")==0){
if (size < width * height * 4){
Py_RETURN_NONE;
}
ret_size = WebPEncodeRGBA(rgb, width, height, 4* width, quality_factor, &output);
} else if (strcmp(mode, "RGB")==0){
if (size < width * height * 3){
Py_RETURN_NONE;
}
ret_size = WebPEncodeRGB(rgb, width, height, 3* width, quality_factor, &output);
} else {
Py_RETURN_NONE;