Cannot convert base64 string into image

Question:

Can someone help me turn this base64 data into image? I don’t know if it’s because the data was not decoded properly or anything else. Here is how I decoded the data:

import base64

c_data = { the data in the link (string type) }

c_decoded = base64.b64decode(c_data)

But it gave the error Incorrect Padding so I followed some tutorials and tried different ways to decode the data.

c_decoded = base64.b64decode(c_data + '=' * (-len(c_data) % 4))

c_decoded = base64.b64decode(c_data + '=' * ((4 - len(c_data) % 4) % 4)

Both ways decoded the data without giving the error Incorrect Padding but now I can’t turn the decoded data into image.
I have tried creating an empty png then write the decoded data into it:

from PIL import Image

with open('c.png', 'wb') as f:
    f.write(c_decoded)
image = Image.open('c.png')
image.show()

It didn’t work and gave the error: cannot identify image file ‘c.png’
I have tried using BytesIO:

from PIL import Image
import io
from io import BytesIO

image = Image.open(io.BytesIO(c_decoded))
image.show()

Now it gave the error: cannot identify image file <_io.BytesIO object at 0x0000024082B20270>
Please help me.

Asked By: gay

||

Answers:

Not sure if you definitely need a Python solution, or you just want help decoding your image like the first line of your question says, and you thought Python might be needed.

If the latter, you can just use ImageMagick in the Terminal:

cat YOURFILE.TXT | magick inline:- result.png

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.

Answered By: Mark Setchell

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)
Answered By: gay
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.