You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3编码PNG为Base64时出现AttributeError问题求助

解决Python3中PNG转Base64时的AttributeError问题

这个问题是因为Python 3和Python 2在Base64编码的处理逻辑上有明显差异,我来帮你修正代码并解释背后的原因:

错误原因分析

你用open(files, 'rb')读取PNG文件后得到的是bytes对象,而encode('base64')是Python 2中字符串对象的方法,Python 3已经移除了这个用法,所以会抛出AttributeError: 'bytes' object has no attribute 'encode'的错误。

修正后的代码

首先要导入Python标准库中的base64模块,然后用正确的方式处理bytes数据的Base64编码:

import os
import base64

for files in os.listdir("."):
    if files.endswith(".png"):
        # 使用with语句自动管理文件资源,避免泄漏
        with open(files, 'rb') as pngFile:
            png_bytes = pngFile.read()
            # 对bytes进行Base64编码,再转成字符串
            base64data = base64.b64encode(png_bytes).decode('utf-8').replace('\n', '')
            base64String = '<image xlink:href="data:image/png;base64,{0}" width="240" height="240" x="0" y="0" />'.format(base64data)
            # 可以在这里添加打印或保存base64String的逻辑
            print(base64String)

关键知识点说明

  • base64.b64encode(png_bytes):接收bytes类型的数据,返回经过Base64编码后的bytes对象
  • .decode('utf-8'):将编码后的bytes对象转换成字符串,这样才能用于后续的字符串格式化
  • 使用with语句打开文件:相比直接open()更安全,会自动在代码块结束后关闭文件

内容的提问来源于stack exchange,提问作者hypadr1v3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:35:26