python - convert binary data to utf-8

2019-06-24 13:55发布

_f = open("c:/go-next.png", "rb")
data = _f.read()
_f.close()
data.encode("utf-8")

# Error: UnicodeDecodeError: file <maya console> line 1: ascii # 

As you see I open a image file, and the data is type. But I have to convert it to utf-8. Maybe binary data has some extra char (or not), it conflict with conversion. Is there any way to solve it?

标签: python utf-8
5条回答
一夜七次
2楼-- · 2019-06-24 14:37

Encoding means converting strings to storable bytes.
And Decoding means converting bytes to readable strings.

The data in your code is already encoded.

查看更多
走好不送
3楼-- · 2019-06-24 14:41

Image cannot be converted into something like charters in utf8.

查看更多
对你真心纯属浪费
4楼-- · 2019-06-24 14:49

Text encodings only apply to text. Do not attempt to use them on binary data.

查看更多
该账号已被封号
5楼-- · 2019-06-24 14:53

You can always map a str to unicode using the latin-1 codec. Once you have a unicode, you can always encode it in utf-8:

data.decode('latin-1').encode("utf-8")
查看更多
ゆ 、 Hurt°
6楼-- · 2019-06-24 14:56

What you're trying to accomplish can probably be achieved by base64 encoding it.

 import base64
 encoded = base64.b64encode(image_binary_data)
查看更多
登录 后发表回答