为什么PIL无法读取自己生成的字节数组?

时间:2018-03-21 16:52:12

标签: python image stream python-imaging-library pillow

考虑这段代码

from io import BytesIO
from PIL import Image

image = Image.open("iamge.jpg") # Read image
image_bytes = image.tobytes() # Covert to bytes

new_image = Image.open(BytesIO(image_bytes)) # Read from BytesIO (Exception!!!)
new_image.show()

执行后我收到此错误:

  

OSError:无法识别图像文件< _io.BytesIO对象位于0x7fa885caf258>

但是当我从打开函数得到普通字节时:

with open("iamge.jpg", "rb") as file_stream:
    image_bytes = file_stream.read()
    image = Image.open(BytesIO(image_bytes))
    image.show()

我没有错误!

如何编写可以处理两种类型字节数组的代码(一个由PIL生成,另一个由'open'生成)?

1 个答案:

答案 0 :(得分:0)

看来如果你想从PIL生成的字节数组中读回来,你需要使用 frombytes 函数:

image2 = Image.open("iamge.jpg")
image_bytes2 = image2.tobytes()

new_image = Image.frombytes("RGB", (image2.width, image2.height), image_bytes2)
new_image.show()

这样做的缺点是您必须知道模式(例如RGB)和图像大小。这仍然是一个未解决的问题。

此外,似乎您不应该使用PIL的tobytes方法。相反,如果你想要字节数组,你应该执行以下操作:

with BytesIO() as output:
    with Image.open("iamge.jpg") as img:
        img.save(output, "jpeg")
    b1 = output.getvalue()

尽管字节数组仍与 open 函数完全相同。