python - Using webp images with Pillow 2.2.2 or 2.3.0 -
i using pillow version 2.2.2 convert webp image jpeg image. webp images stored in memory buffer. found when try tom open webp image cause memory leak large number of images become real problem.
def webp_to_jpeg(raw_img): image = image.open(stringio.stringio(raw_img)) buffer = stringio.stringio() image.save(buffer, "jpeg") return string_buffer.getvalue()
this memory leak happen when work webp images. try update pillow 2.3.0 when did not able read webp images @ , got following exception "webp unknown extension"
it's webp decoder bug in pillow (see here). it's still leaking memory in version 2.4.0
the workaround i've found based on python-webm. 1 leaking memory too, can fix it:
in encode.py, import libc free() function :
from ctypes import cdll, c_void_p libc = cdll(find_library("c")) libc.free.argtypes = (c_void_p,) libc.free.restype = none
then modify _decode()
free buffer allocated in webp decoder .dll:
def _decode(data, decode_func, pixel_sz): bitmap = none width = c_int(-1) height = c_int(-1) size = len(data) bitmap_p = decode_func(str(data), size, width, height) if bitmap_p not none: # copy decoded data buffer width = width.value height = height.value size = width * height * pixel_sz bitmap = create_string_buffer(size) memmove(bitmap, bitmap_p, size) #free wepb decoder buffer! libc.free(bitmap_p) return (bytearray(bitmap), width, height)
to convert rgb webp image :
from webm import decode def rgbwebp_to_jpeg(raw_img): result = decode.decodergb(raw_img) if result not none: image = image.frombuffer('rgb', (result.width, result.height), str(result.bitmap),'raw', 'rgb', 0, 1) buffer = stringio.stringio() image.save(buffer, "jpeg") return buffer.getvalue()
Comments
Post a Comment