【问题标题】:when convert to base 64, TypeError: 'str' does not support the buffer interface [duplicate]转换为 base 64 时,TypeError:'str' 不支持缓冲区接口 [重复]
【发布时间】:2015-01-25 10:36:43
【问题描述】:
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)时它显示错误。我该如何解决这个问题?

【问题讨论】:

    标签: python base64


    【解决方案1】:
    encodedMsg = base64.b64encode(self.msg.encode('ascii'))
    

    参考:Base64 encoding in Python 3

    【讨论】:

      【解决方案2】:

      简而言之,这是因为在 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,一切都应该正常。

      【讨论】:

      • 我从 xml 文件中读取了一些数据。此代码self.msg = base64.b64decode(self.xml.encode('utf-8')) 返回File "/opt/python3/current/lib/python3.4/base64.py", line 90, in b64decode return binascii.a2b_base64(s) binascii.Error: Incorrect padding
      猜你喜欢
      • 2018-04-16
      • 1970-01-01
      • 2011-07-25
      • 2014-08-09
      • 2023-03-10
      • 1970-01-01
      相关资源
      最近更新 更多