Byte stream and utf-8 in python 3

落爺英雄遲暮 提交于 2019-12-11 14:29:30

问题


I am reading a blob from a database which contains a png file.

The blob looks correct and is of a bytes data type. It starts:

b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x92\x00\x00\x00m\x08\x06\x00\x00\x00J\xbf8B\x00\x00\x00\x06bKGD\x00\x00\x00\x00\x00\x00\xf9C\xbb\x7f\x00\x00\x00\tpHYs\x00\x00\x0b\x13\x00\x00\

However, when I perform:

image = wx.Image(blob)

I get the message:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

It seems to be treating the bytes as a string, but why?


回答1:


wx.Image() does not support creating an image from a raw byte stream. The class has instead interpreted it as a filename (which must be a string, so it is being decoded).

Wrap your data in a io.BytesIO() object; wx accepts such objects as streams:

import io

image = wx.Image(io.BytesIO(blob))


来源:https://stackoverflow.com/questions/46862214/byte-stream-and-utf-8-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!