2

我正在使用枕头版本 2.2.2 将 webp 图像转换为 jpeg 图像。webp 图像存储在内存缓冲区中。我发现当我尝试打开 webp 图像时,它会导致大量图像的内存泄漏成为一个真正的问题。

def webp_to_jpeg(raw_img):
 image =  Image.open(StringIO.StringIO(raw_img))
 buffer = StringIO.StringIO()
 image.save(buffer, "JPEG")
 return string_buffer.getvalue()

这种内存泄漏仅在我使用 webp 图像时发生。我尝试将枕头更新到 2.3.0,但是当我这样做时,我根本无法读取 webp 图像,并且出现以下异常“WEBP 未知扩展”

4

2 回答 2

3

这是 PILLOW 中的一个 webp 解码器错误(请参见此处)。在 2.4.0 版本中它仍然在泄漏内存

我发现的唯一解决方法是基于python-webm。这也泄漏了内存,但您可以修复它:

在 encode.py 中,导入 libc free() 函数:

from ctypes import CDLL, c_void_p
libc = CDLL(find_library("c"))
libc.free.argtypes = (c_void_p,)
libc.free.restype = None

然后修改_decode()释放在 webp 解码器 .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 is not None:
        # Copy decoded data into a buffer
        width = width.value
        height = height.value
        size = width * height * pixel_sz
        bitmap = create_string_buffer(size)

        memmove(bitmap, bitmap_p, size)

        #Free the wepb decoder buffer!
        libc.free(bitmap_p)

    return (bytearray(bitmap), width, height)

要转换 RGB webp 图像:

from webm import decode

def RGBwebp_to_jpeg(raw_img):
    result = decode.DecodeRGB(raw_img)
    if result is 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()
于 2014-05-30T18:16:34.117 回答
1

Pillow 2.3.0 在读取更改日志时修复了一些内存泄漏:

Fixed memory leak saving images as webp when webpmux is available [cezarsa]

据我所知,枕头依靠 os webp 支持。

你试过这个吗?https://stackoverflow.com/a/19861234/756056

于 2014-02-23T02:07:06.883 回答