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

Python报错LookupError: 'base64'非文本编码,求解决方案

解决LookupError: 'base64' is not a text encoding的问题

这个问题我之前也碰到过,本质是Python3对文本编码和字节编码的区分更严格了——原来Python2里的img.decode('base64')写法在Python3里已经不适用了,因为base64不属于UTF-8、ASCII这类文本编码,它是一种字节级的编码方式,所以直接用字符串的decode()方法会抛出这个错误。

具体修复步骤

1. 替换依赖模块

首先,你需要导入base64模块(专门处理base64编解码),同时把StringIO换成BytesIO——因为base64解码后得到的是图片二进制数据,StringIO只处理文本字符串,而BytesIO才能处理二进制流。

from base64 import b64decode
from io import BytesIO

2. 修改解码逻辑

把原来的这行代码:

image_string = StringIO(img.decode('base64'))

替换成以下逻辑,根据你的img类型做对应处理:

  • 如果img是字节串(bytes类型)(比如从POST请求的二进制数据里获取的):

    decoded_img = b64decode(img)
    image_string = BytesIO(decoded_img)
    
  • 如果img是字符串(str类型)(比如直接从HTML表单里拿到的base64文本):

    # 先把字符串转成字节串,再解码
    img_bytes = img.encode('utf-8')
    decoded_img = b64decode(img_bytes)
    image_string = BytesIO(decoded_img)
    

3. 完整的resize函数示例

修改后的resize函数大概是这样的(假设你用PIL处理图片):

from base64 import b64decode, b64encode
from io import BytesIO
from PIL import Image

def resize(photo_data, width, height):
    # 处理输入数据:字符串转字节,字节直接使用
    if isinstance(photo_data, str):
        img_bytes = photo_data.encode('utf-8')
    else:
        img_bytes = photo_data
    
    # 解码base64得到图片二进制数据
    decoded_img = b64decode(img_bytes)
    # 用BytesIO模拟文件流供PIL读取
    image_stream = BytesIO(decoded_img)
    
    # 正常执行图片缩放逻辑
    img = Image.open(image_stream)
    img.thumbnail((width, height))
    
    # 如果需要把缩放后的图片再转成base64嵌入HTML,这么做:
    output_buffer = BytesIO()
    img.save(output_buffer, format='JPEG')  # 根据你的图片格式调整(PNG/JPEG等)
    resized_base64 = b64encode(output_buffer.getvalue()).decode('utf-8')
    
    return resized_base64

为什么这么改?

  • Python3中,str.decode()只针对文本编码(用于把字节串解码成字符串),而base64是字节到字节的编码,必须用专门的base64.b64decode()处理。
  • BytesIO可以把二进制数据包装成类文件对象,这样PIL等图像处理库就能像读取本地文件一样读取图片数据。

另外,错误提示里提到的codecs.decode()也能实现,但base64.b64decode()更直观、更常用,所以优先推荐这种写法。

内容的提问来源于stack exchange,提问作者anurag kumar anu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:18:39