从字节文件打开 PIL 图像

Open PIL image from byte file

我有 this image 大小为 128 x 128 像素和 RGBA 作为字节值存储在我的内存中。但是

from PIL import Image

image_data = ... # byte values of the image
image = Image.frombytes('RGBA', (128,128), image_data)
image.show()

抛出异常

ValueError: not enough image data

为什么?我做错了什么?

The documentation for Image.open 表示它可以接受类似文件的对象,因此您应该能够传入从包含编码图像的 bytes 对象创建的 io.BytesIO 对象:

from PIL import Image
import io

image_data = ... # byte values of the image
image = Image.open(io.BytesIO(image_data))
image.show()

你可以试试这个:

image = Image.frombytes('RGBA', (128,128), image_data, 'raw')
Source Code:
def frombytes(mode, size, data, decoder_name="raw", *args):
    param mode: The image mode.
    param size: The image size.
    param data: A byte buffer containing raw data for the given mode.
    param decoder_name: What decoder to use.