Python base64 解码图片无效

Python Decode base64 to picture not working

我得到了从应用程序发送到我的 redis 服务器的图像的以下 Base64 表示形式: https://1drv.ms/t/s!AkTtiXv5QMtWliMbeziGpd0t1EjW?e=JDHEkt

以下是为不想下载整个 13MB 数据文件的用户摘录的数据:

b'\/9j\/4b6URXhpZgAASUkqAAgAAAAMAAABBAABAAAAoA8AAAEBBAABAAAAuAsAAA8BAgAIAAAAngAA\nABABAgAJAAAApgAAABIBAwABAAAAAQAAABoBBQABAAAA0gAAABsBBQABAAAA2gAAACgBAwABAAAA\nAgAAADEBAgAOAAAAsAAAADIBAgAUAAAAvgAAABMCAwABAAAAAQAAAGmHBAABAAAA4gAAAIQCAABz\nYW1

我尝试用以下方法修复 b64:

import base64

with open('Outputfirst.txt', 'r') as file:
    imgstring = file.read().replace('\n', '')

#get rid of wrong characters
imgstring = imgstring.replace("b'",'')
imgstring = imgstring.replace('\','')
imgstring = imgstring.replace('"','')
imgstring = imgstring.replace('\'','')
imgstring = imgstring.replace(',','')
#take care of padding
if(len(imgstring)%4 ==1):
    imgstring = imgstring +"==="
if(len(imgstring)%4 ==2):
    imgstring = imgstring +"=="
if(len(imgstring)%4 ==3):
    imgstring = imgstring +"="

imgstring = bytes(imgstring,'utf8')

with open(filename, 'wb') as f:
    f.write(imgstring)
    
imgdata = base64.b64decode(imgstring)
filename = 'some_image3.jpg' 
with open(filename, 'wb') as f:
    f.write(imgdata) 

但不知何故我没有正确恢复图像。

当我通过 https://base64.guru/tools/repair 使用此工具并将其输出作为我的脚本的输入时,我得到了我想要的图像。

似乎\n没有被过滤掉。

整个过滤和填充可以像这样完成:

with open('Outputfirst.txt', 'r') as file:
    imgstring = file.read().replace('\n', '').replace('\','').replace("b'",'')
    imgstring = imgstring + '=' * (4 - len(imgstring) % 4)

填充 3 个“=”无效:

if(len(imgstring)%4 ==1):
    imgstring = imgstring +"==="