3

I'm receiving an image from a form in base64 which I would like to convert back to a PNG file type.

To do this I tried the following methods

attempt1 = base64.b64decode(picture.data)
attempt2 = picture.data.decode('base64')

but I received the error Error: Incorrect padding.

I saw this answer and tried using the function however I get the same error.

What can I do to fix this issue? Thanks.

Edit

my base64 image looks like this (The list of characters are much longer):

data:image/png;base64, OouhoGUiyf+YdiHl==
Community
  • 1
  • 1
Pav Sidhu
  • 6,724
  • 18
  • 55
  • 110
  • Maybe you could provide some information about the data you have, how many characters is it? Does it end with a series of `=`? – jojonas Sep 06 '15 at 22:42
  • Did you exclude the `data:image/png;base64, ` part from your decoding procedure? – jojonas Sep 06 '15 at 22:55
  • 1
    What part of the string are you passing in to be decoded? The "data" in your example is `OouhoGUiyf+YdiHl==`, nothing more, nothing less. – Jeff Mercado Sep 06 '15 at 22:55
  • @jojonas I'm not excluding the `data:image/png;base64, ` part. I'm guessing I should now? Maybe using regex? – Pav Sidhu Sep 06 '15 at 22:57
  • 1
    @JeffMercado Good guess. @jojonas There is no need for regex here. A simple `str.split` or manual offset (by using `str.find`), by looking for the comma should do its job. – HelloWorld Sep 06 '15 at 22:59
  • 1
    @HelloWorld That works perfectly, thanks for the input. – Pav Sidhu Sep 06 '15 at 23:03
  • @HelloWorld, could you please post your comments as an answer so Pav Sidhu can mark it as solved? – Montmons Mar 28 '17 at 12:25

1 Answers1

3

It seems that your data is a DataURL scheme

Data URLs are composed of four parts: a prefix (data:), a MIME type indicating the type of data, an optional base64 token if non-textual, and the data itself:

data:[<mediatype>][;base64],<data>

You should extract only the <data> part from your string:

base64.decodebytes(picture.data.split(",")[1])
Alexander
  • 12,424
  • 5
  • 59
  • 76