代码之家  ›  专栏  ›  技术社区  ›  hypadr1v3

将PNG图像编码为Base64时的AttributeError

  •  1
  • hypadr1v3  · 技术社区  · 8 年前

    我正在尝试使用以下代码将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

    2 回复  |  直到 8 年前
        1
  •  1
  •   hypadr1v3    8 年前

    好我不知道是否应该将此标记为一个答案,但我使用Python 2.7实现了它。原因不明。

        2
  •  0
  •   F.Igor    8 年前

    尝试使用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)