将PNG图像编码为Base64时出现AttributeError
AttributeError when encoding PNG image into Base64
我正在尝试使用以下代码将 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'
我试过很多这样的解决方案:
但它只是抛出另一个错误。顺便说一句,我正在使用 python 3
尝试使用 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)
好吧...我不知道是否应该将其标记为答案,但我使用 Python 2.7 使其正常工作。原因未知。
我正在尝试使用以下代码将 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'
我试过很多这样的解决方案:
尝试使用 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)
好吧...我不知道是否应该将其标记为答案,但我使用 Python 2.7 使其正常工作。原因未知。