1

I am trying to decode an image I select from a directory. Once the image is selected I need to decode the encoded string.

I keep getting the error 'incorrect padding'.

Below is the code and the encoded string when I print it.

encoded = message['image']
decoded = base64.b64decode(encoded)

Here is the string: Its a big string so I hosted it here. https://www.scribd.com/document/402282670/String

The string starts with

data:image/png;base64,iVBORw0KGgoAAAANSUh
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
Gavin Everett
  • 31
  • 1
  • 7
  • The answer to this question, is this other answer https://stackoverflow.com/a/6102526/6110285 I'd say this is a duplicate of [this question](https://stackoverflow.com/questions/6102311/python-b64decode-incorrect-padding) Basically base64 encodes 3 bytes into 4, so if the padding (***=*** character) leaves out 1 or 2 bytes from the decoding, the error you mention is raised – pittix Mar 18 '19 at 19:18

1 Answers1

1

Incorrect padding error is caused because sometimes, metadata is also present in the encoded string. If your string looks something like: 'data:image/png;base64,...base 64 stuff....' then you need to remove the first part before decoding it.

Say if you have image base64 encoded string, then try below snippet..

from PIL import Image
from io import BytesIO
from base64 import b64decode
im = Image.open(BytesIO(b64decode(encoded .split(',')[1])))
im.save("image.png")

Otherwise, you can simply write it as

with open(filename, 'wb') as image_file:
    image_file.write(b64decode(encoded.split(',')[1]))
sam
  • 2,263
  • 22
  • 34