Strange behaviour when converting base64 string to png in Python

时间:2018-04-18 17:57:23

标签: python base64 png

Hello I'm new to the concept of base64 images. I was trying to convert base64 "links" in a HTML to png files in Python, but the png generated seems to be damaged and I don't know why... Here is my code (in python 3.6)

encoded = (string2[0].split(",")[1]).encode("utf-8")
with open(r"myDirectory\example1.png", "wb") as fh:
    fh.write(base64.decodebytes(encoded))

string2[0] is the full base64 string which I copied from the HTML. i.e. something like

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA0gAA...K5C%0AYII=

The problem is essentially the following: A png file will be generated, but when I open it, windows says "the file appears to be damaged, corrupted". However strangely when I open this base64 string in google chrome, the photo can be shown.

Anyone has encountered similar situation before?

p.s. I was thinking to provide the full base64 string, but it's very very long. Anyone knows how to paste such a long string to the question? e.g. a "dragable box of code" similar to what the OP has done in this question

Edit: The base64 string can be found here. My first time sharing documents in google drive - let me know if you guys can access it.

0 个答案:

没有答案
相关问题