简体   繁体   English

Python 解码 base64 到图片不工作

[英]Python Decode base64 to picture not working

I have got the following Base64 representation of an image I get send to my redis server from an application: https://1drv.ms/t/s?AkTtiXv5QMtWliMbeziGpd0t1EjW?e=JDHEkt I have got the following Base64 representation of an image I get send to my redis server from an application: https://1drv.ms/t/s?AkTtiXv5QMtWliMbeziGpd0t1EjW?e=JDHEkt

Here's an excerpt of the data for those who don't want to download the whole 13MB data file:对于不想下载整个 13MB 数据文件的人,以下是数据摘录:

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

I tried to repaire the b64 with the following:我尝试使用以下方法修复 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) 

But somehow I dont get the image back properly.但不知何故,我没有正确恢复图像。

When I use this tool though https://base64.guru/tools/repair and take its output as input for my script, I get the image I want.当我通过https://base64.guru/tools/repair使用此工具并将其 output 作为我的脚本的输入时,我得到了我想要的图像。

It seems \\n doesn't get filtered out.似乎\\n没有被过滤掉。

The whole filtering and padding can be done like so:整个过滤和填充可以这样完成:

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

Padding with 3 '=' is invalid:使用 3 '=' 填充无效:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM