mitchkman
mitchkman

Reputation: 6680

Issue with base64 to binary conversion

I have a base64 string and would like to write it to a file as a JPEG, using Python 3.

file = request.json['file'] 
prefix = 'data:' + file['filetype'] + ';base64,' 
full_base64 = prefix + file['base64']
# full_base64 = data:image/jpeg;base64,/9j/4AAQSkZJ....
# base 64 verified with http://codebeautify.org/base64-to-image-converter

file_data = b64decode(full_base64)

with open('uploads/' + str(uuid.uuid4()) + '.jpeg', 'wb') as file:
    file.write(file_data)

But if I try to open the file using an image viewer, I get this error:

Error interpreting JPEG image file (Not a JPEG file: starts with 0x75 0xab)

The base64 string seems to be correct (I verified it using http://codebeautify.org/base64-to-image-converter), so the issue must be with b64encode or with writing the file.

Thank you

Upvotes: 1

Views: 843

Answers (1)

mhawke
mhawke

Reputation: 87074

If you want to create a valid JPEG file that can be read by image viewers then you should not be prepending the data URI to the file. You still need to decode the base64 encoded image data though.

with open('uploads/' + str(uuid.uuid4()) + '.jpeg', 'wb') as f:
    f.write(b64decode(file['base64']))

This will produce JPEG file that can be opened by standard image viewers.

Also, be careful of you use as file as a variable name - it shadows the builtin file.

If for some reason you want to create files that contain the data URI, for example to be easily inserted into HTML or CSS files, then you do not need to decode the incoming JPEG data - it's already base64 encoded:

image = request.json['file'] 
prefix = 'data:' + image['filetype'] + ';base64,' 
data_URI = prefix + image['base64']
# data_URI = data:image/jpeg;base64,/9j/4AAQSkZJ....

with open('uploads/' + str(uuid.uuid4()) + '.jpeg', 'wb') as f:
    f.write(data_URI)

This simply prepends the data URI prefix to the already base64 encoded data, and writes that to a file.

Upvotes: 2

Related Questions