1

我正在尝试使用以下代码将 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 对 pdf 文件进行编码,但它只会引发另一个错误。顺便说一句,我正在使用 python 3

4

2 回答 2

1

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

于 2018-08-07T11:37:29.877 回答
-1

尝试使用 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)
于 2018-05-31T04:55:02.583 回答