本文介绍了python 3中的字节流和utf-8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从包含 png 文件的数据库中读取 blob.
I am reading a blob from a database which contains a png file.
blob 看起来正确并且是字节数据类型.它开始:
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\
但是,当我执行:
image = wx.Image(blob)
我收到消息:
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?
推荐答案
wx.Image()
不支持从原始字节流创建图像.该类将其解释为文件名(必须是字符串,因此正在对其进行解码).
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).
将数据包装在 io.BytesIO()
对象中;wx
接受像流这样的对象:
Wrap your data in a io.BytesIO()
object; wx
accepts such objects as streams:
import io
image = wx.Image(io.BytesIO(blob))
这篇关于python 3中的字节流和utf-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!