jas jas - 28 days ago 10
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:
fh.write(base64.decodestring(imgData))


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

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:

fh.write(base64.decodestring(imgData.encode('ascii')))

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.

Comments