Python将base64解码为图片不工作

2024-09-29 01:35:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我已获得从应用程序发送到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使用这个工具并将其输出作为脚本的输入时,我得到了我想要的图像


Tags: ofhttps图像lenifaswithopen
1条回答
网友
1楼 · 发布于 2024-09-29 01:35:51

似乎\\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 +"==="

相关问题 更多 >