【问题标题】:AttributeError when encoding PNG image into Base64将PNG图像编码为Base64时出现AttributeError
【发布时间】:2018-05-31 04:38:10
【问题描述】:

我正在尝试使用以下代码将 PNG 图像编码为 Base64:

for files in os.listdir("."):
if files.endswith(".png"):
    pngFile = open(files, 'rb')
    base64data = pngFile.read().encode('base64').replace('\n','')
    base64String = '<image xlink:href="data:image/png;base64,{0}" width="240" height="240" x="0" y="0" />'.format(base64data)

但是当我使用它时,它会报错:

AttributeError: 'bytes' object has no attribute 'encode'

我已经尝试了很多这样的解决方案: AttributeError: 'bytes' object has no attribute 'encode'; base64 encode a pdf file 但它只会引发另一个错误。顺便说一句,我正在使用 python 3

【问题讨论】:

标签: python python-3.x encoding base64 attributeerror


【解决方案1】:

嗯...我不知道我是否应该将此标记为答案,但我使用 Python 2.7 让它工作。原因不明。

【讨论】:

    【解决方案2】:

    尝试使用 base64 库

    import base64
    
    with open(files, "rb") as image_file:
        base64data = base64.b64encode(image_file.read())
        base64String = '<image xlink:href="data:image/png;base64,{0}" width="240" height="240" x="0" y="0" />'.format(base64data)
    

    【讨论】:

    • 这不起作用,它给了我TypeError: a bytes-like object is required, not 'str' ,这意味着您提供的解决方案以某种方式将我的文件转换为字符串,但它没有任何意义
    猜你喜欢
    • 2011-10-21
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多