问题
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