Home > Mobile >  Cannot convert base64 string into image
Cannot convert base64 string into image

Time:10-02

Can someone help me turn enter image description here

Or equivalently and avoiding "Useless Use of cat":

magick inline:- result.png < YOURFILE.TXT

If the former, you can use something like this (untested):

from urllib import request

with request.urlopen('data:image/png;base64,iVBORw0...')  as response:
   im = response.read()

Now im contains a PNG-encoded [^1] image, so you can either save to disk as such:

with open('result.png','wb') as f:
    f.write(im)

Or, you can wrap it in a BytesIO and open into a PIL Image:

from io import BytesIO
from PIL import Image

pilImage = Image.open(BytesIO(im))

[^1]: Note that I have blindly assumed it is a PNG, it may be JPEG, so you should ideally look at the start of the DataURI to determine a suitable extension for saving your file.

CodePudding user response:

Credit to @jps for explaining why my code didn't work. Check out @Mark Setchell solution for the reliable way of decoding base64 data (his code fixes my mistake that @jps pointed out)

So basically remove the [data:image/png;base64,] at the beginning of the base64 string because it is just the format of the data. Change this:

c = "data:image/png;base64,iVBORw0KGgoAAAANSUh..."

to this:

c = "iVBORw0KGgoAAAANSUh..."

and now we can use

c_decoded = base64.b64decode(c)
  • Related