转换为基64时,TypeError:“str”不支持

2024-04-18 10:23:23 发布

您现在位置:Python中文网/ 问答频道 /正文

im = Image.open(filePath)                     # load image
self.msg = str(bytearray(list(im.getdata()))) # convert image data to string
encodedMsg = base64.b64encode(self.msg)

当我试图将从图像读取的数据编码为base64时,它返回一个错误:

File "Steganography.py", line 42, in msgToXml
    encodedMsg = base64.b64encode(self.msg)
  File "/opt/python3/current/lib/python3.4/base64.py", line 62, in b64encode
    encoded = binascii.b2a_base64(s)[:-1]
TypeError: 'str' does not support the buffer interface

当我在家使用Ubuntu(python 2.7)时,它就工作了。但当我使用学校机器(python3.4)时它显示错误。我该怎么解决?


Tags: inpyimageself错误linemsgopen
2条回答
encodedMsg = base64.b64encode(self.msg.encode('ascii'))

引用:Base64 encoding in Python 3

简而言之,这是因为在Python3中对unicode/string/bytes系统进行了一次重大的改革。你应该阅读这个https://docs.python.org/3.0/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit和这个https://docs.python.org/3.3/howto/unicode.html来理解发生了什么以及如何处理它。

要回答你的具体问题-如果你不把你的bytearray转换成str,一切都应该正常。

相关问题 更多 >