简体   繁体   English

将Base64字符串另存为.PNG不起作用

[英]Saving Base64 String as .PNG not working

I have a base64 string that I got from using Google Charts. 我有一个使用Google图表获得的base64字符串。 The project is being written in Python/Django/Javascript if that helps. 如果有帮助,可以使用Python / Django / Javascript编写该项目。

chartStr = chart.getImageURI()

I want to save this string as a .png on my server. 我想将此字符串另存为.png在我的服务器上。

I've tried 我试过了

with open('foo.png',"wb") as f:
    f.write(chartStr.decode('base64'))

but I get an incorrect padding error. 但是我得到了一个错误的填充错误。 I fix this by adding a '=' at the end of the string chartStr. 我通过在字符串chartStr的末尾添加“ =”来解决此问题。 WHen I do that, the foo.png image is created but when I try to open it I get an error that says 我这样做时,会创建foo.png图像,但是当我尝试打开它时,出现错误提示

Fatal error reading PNG image file: Not a PNG file 读取PNG图像文件时发生致命错误:不是PNG文件

Any advice? 有什么建议吗? Thanks! 谢谢!

When you added the = to the string the returned string from .decode("base64") was the same as the input string minus the appended = . =添加到字符串时,从.decode("base64")返回的字符串与输入字符串减去附加的=

To write the .png to a file you need to do the following: 要将.png写入文件,您需要执行以下操作:

head, data = chartStr.split(",", 1)
with open('foo.png',"wb") as f:
     f.write(data.decode('base64'))

This removes the data:image/png;base64, stuff and leaves you with some base64 encoded data. 这将删除data:image/png;base64,并留下一些base64编码的数据。

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

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