4

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"

How can I convert such a PNG string to a binary PNG file in python 3 ?

logical x 2
  • 311
  • 4
  • 18

1 Answers1

6

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()))

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.

user1318499
  • 1,327
  • 11
  • 33
logical x 2
  • 311
  • 4
  • 18