jas jas - 1 year ago 89
Python Question

Error while saving base64 encoded image to the filesystem

I have tried to follow this example to save a base64 encoded image I receive in a HTTP request, to the filesystem:

imgData = re.sub('^data:image/.+;base64,', '', inner_data['output']['image'])

with open("imageToSave.png", "wb") as fh:

I have printed the string I'm trying to decode and it seems to be correct.

/9j/4AAQSkZJRgABAQAAAQABAAD/ [...] /+bax2njPQ8daytViRZP7UQbbmGRVEg6sPf1qYK0bCnKzuf/Z

But I keep getting this error

TypeError: expected bytes-like object, not str

Answer Source

The base64.decodestring() function expects bytes, not a str object. You'll need to encode your base64 string to bytes first. Since all characters in such a string are ASCII characters, just use that codec:


From the base64.decodestring() documentation:

Decode the bytes-like object s, which must contain one or more lines of base64 encoded data, and return the decoded bytes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download