0

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
Community
  • 1
  • 1
jas
  • 1,539
  • 5
  • 17
  • 30

1 Answers1

4

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343