Open PIL image from byte file

Michael Dorner picture Michael Dorner · Oct 2, 2015 · Viewed 83.2k times · Source

I have this image with size 128 x 128 pixels and RGBA stored as byte values in my memory. But

from PIL import Image

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

throws the exception

ValueError: not enough image data

Why? What am I doing wrong?

Answer

Colonel Thirty Two picture Colonel Thirty Two · Oct 2, 2015

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()