Ela*_*n M 18 python bytesio pillow
我正在使用PIL的Pillow fork并继续收到错误
OSError:无法在0x103a47468>处识别图像文件<_io.BytesIO对象
当试图打开图像时.我使用virtualenv与python 3.4并没有安装PIL.
我试图根据遇到同样问题的其他人找到解决方案,然而,这些解决方案对我不起作用.这是我的代码:
from PIL import Image
import io
# This portion is part of my test code
byteImg = Image.open("some/location/to/a/file/in/my/directories.png").tobytes()
# Non test code
dataBytesIO = io.BytesIO(byteImg)
Image.open(dataBytesIO) # <- Error here
Run Code Online (Sandbox Code Playgroud)
图像存在于文件的初始打开中,并转换为字节.这似乎适用于几乎所有人,但我无法弄清楚为什么它失败了.
编辑:
dataBytesIO.seek(0)
Run Code Online (Sandbox Code Playgroud)
因为我不是通过流保存图像,所以我不是通过流保存图像,因此我只是用数据实例化BytesIO,因此(如果我正确地想到这一点),搜索应该已经为0.
sdi*_*kby 19
(这个解决方案来自作者本人.我刚刚把它移到了这里.)
解:
# This portion is part of my test code
byteImgIO = io.BytesIO()
byteImg = Image.open("some/location/to/a/file/in/my/directories.png")
byteImg.save(byteImgIO, "PNG")
byteImgIO.seek(0)
byteImg = byteImgIO.read()
# Non test code
dataBytesIO = io.BytesIO(byteImg)
Image.open(dataBytesIO)
Run Code Online (Sandbox Code Playgroud)
问题在于Image.tobytes()返回字节对象的方式.它似乎是无效的数据,并且'编码'不能是除了raw之外的任何东西,它仍然会出现输出错误的数据,因为几乎每个字节都出现在格式中\xff\.但是,通过BytesIO保存字节并使用该.read()函数读取整个图像会得到正确的字节,以后可以实际使用.