从字节文件打开 PIL 图像

我有大小为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()

引发异常

图像数据不足

为什么? 我做错了什么?

159151 次浏览

The documentation for Image.open says that it can accept a file-like object, so you should be able to pass in a io.BytesIO object created from the bytes object containing the encoded image:

from PIL import Image
import io


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

You can try this:

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.