PIL无法识别io.BytesIO对象的图像文件 [英] PIL cannot identify image file for io.BytesIO object

查看:2599
本文介绍了PIL无法识别io.BytesIO对象的图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PIL的枕头叉,并继续收到错误

I am using the Pillow fork of PIL and keep receiving the error

OSError:无法识别图像文件< _xio_BytesIO对象位于0x103a47468>

OSError: cannot identify image file <_io.BytesIO object at 0x103a47468>

当尝试打开图像时.我正在将virtualenv与python 3.4一起使用,并且未安装PIL.

when trying to open an image. I am using virtualenv with python 3.4 and no installation of PIL.

我试图根据其他遇到相同问题的人来找到解决方案,但是这些解决方案对我不起作用.这是我的代码:

I have tried to find a solution to this based on others encountering the same problem, however, those solutions did not work for me. Here is my code:

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

图像最初存在于文件的开头,并且被转换为字节.这似乎适用于几乎所有其他人,但我不知道为什么它对我失败.

The image exists in the initial opening of the file and it gets converted to bytes. This appears to work for almost everyone else but I can't figure out why it fails for me.

dataBytesIO.seek(0)

不能用作解决方案(尝试过),因为我没有通过流保存图像,我只是用数据实例化BytesIO,因此(如果我正确考虑的话)搜寻应该已经在0.

does not work as a solution (tried it) since I'm not saving the image via a stream, I'm just instantiating the BytesIO with data, therefore (if I'm thinking of this correctly) seek should already be at 0.

推荐答案

(此解决方案来自作者本人.我刚刚将其移至此处.)

(This solution is from the author himself. I have just moved it here.)

解决方案:

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

问题在于Image.tobytes()返回字节对象的方式.它似乎是无效数据,并且编码"不能是原始数据,因为原始数据几乎每个字节都以\xff\格式出现,因此原始数据仍然显示出错误的数据.但是,通过BytesIO保存字节并使用.read()函数读取整个图像可以提供正确的字节,以便以后可以实际使用.

The problem was with the way that Image.tobytes()was returning the byte object. It appeared to be invalid data and the 'encoding' couldn't be anything other than raw which still appeared to output wrong data since almost every byte appeared in the format \xff\. However, saving the bytes via BytesIO and using the .read() function to read the entire image gave the correct bytes that when needed later could actually be used.

这篇关于PIL无法识别io.BytesIO对象的图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆