将 base64 编码图像保存到文件系统时出错

Error while saving base64 encoded image to the filesystem

我已尝试按照此 example 将我在 HTTP 请求中收到的 base64 编码图像保存到文件系统:

imgData = re.sub('^data:image/.+;base64,', '', inner_data['output']['image'])

with open("imageToSave.png", "wb") as fh:
    fh.write(base64.decodestring(imgData))

我已经打印了我要解码的字符串,它似乎是正确的。

/9j/4AAQSkZJRgABAQAAAQABAAD/ [...] /+bax2njPQ8daytViRZP7UQbbmGRVEg6sPf1qYK0bCnKzuf/Z

但我一直收到此错误

TypeError: expected bytes-like object, not str

base64.decodestring() 函数需要 字节 ,而不是 str 对象。您需要先将 base64 字符串编码为字节。由于此类字符串中的所有字符都是 ASCII 字符,因此只需使用该编解码器即可:

fh.write(base64.decodestring(imgData.encode('ascii')))

来自base64.decodestring() documentation

Decode the bytes-like object s, which must contain one or more lines of base64 encoded data, and return the decoded bytes.