Python:将通过toDataURL获得的PNG字符串转换为二进制PNG文件 [英] Python: Convert PNG string obtained via toDataURL to binary PNG file
问题描述
toDataURL方法(请参见例如 https://developer.mozilla .org/de/docs/Web/API/HTMLCanvasElement/toDataURL )给出了以下格式的PNG的字符串表示形式:
The toDataURL method (see e.g. https://developer.mozilla.org/de/docs/Web/API/HTMLCanvasElement/toDataURL) gives a string representation of a PNG of the following form:
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby
blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"
如何在python 3中将这样的PNG字符串转换为二进制PNG文件?
How can I convert such a PNG string to a binary PNG file in python 3 ?
推荐答案
好的,所以这是我犯的一个简单(也许是愚蠢的)错误.逗号之前的第一部分,即data:image/png; base64必须删除,像这样
OK, so it was a simple (and maybe stupid) mistake that I made. The first part before the comma, i.e. data:image/png;base64 must be removed, like this
import base64
with open('sample.png', 'wb') as f:
f.write(base64.decodestring(string.split(',')[1].encode()))
对我有用.因此,您需要删除标题是一个明显的错误.但是,如果其他人也碰巧发生在我身上,我仍然会保留它作为答案.还要查看此线程 Python:Python:忽略base64解码时的错误填充"错误关于填充.
does the trick for me. So it is an obvious mistake that you need to remove the header. But I will still leave this as an answer in case it happens to others just as it happened to me. Also look at this thread Python: Ignore 'Incorrect padding' error when base64 decoding concerning padding.
这篇关于Python:将通过toDataURL获得的PNG字符串转换为二进制PNG文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!