Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Base 64 String to BytesIO

Thanks to anyone that can help with this, its my first question so hopefully it's not super obvious.

I Have an image that's being passed as a base64 string (using slim image cropper). I want to convert that to a file then send it to Google Storage as a blob.

Previously I've been just sending the file like below

image = request.files.get('image')
client = _get_storage_client()
bucket = client.bucket(current_app.config['CLOUD_STORAGE_BUCKET'])
blob = bucket.blob(filename)

blob.upload_from_string(
    image.read(),
    content_type=content_type)

Now I'm dealing with the below code.

cropped_image = json.loads(request.form.get('slim[]'))
data = cropped_image['output']['image']

data variable is a string:

data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD...'

i'm stuck not sure if I need to encode to base64, decode from base64, turn it to a bytestring then encode/decode??

I've tried just sending it as is using bytesIO and StringIO

image = BytesIO(data)
blob.upload_from_string(
    image.read(),
    content_type=content_type)

and I get a black picture uploaded, really try to not ask questions without researching first but this one has me stumped.

Thanks.

like image 531
Solutionist Avatar asked Aug 15 '17 02:08

Solutionist


1 Answers

re.sub("data:image/jpeg;base64,", '', b64_str).decode("base64") works in Python2. In Py 2, the str is bytes actually.

UPDATE

from base64 import b64decode

with open("test.jpeg", 'wb') as f:
    f.write(b64decode(re.sub("data:image/jpeg;base64,", '', b64_str)))

# or

image = BytesIO(b64decode(re.sub("data:image/jpeg;base64", '', b64_str)))
like image 128
stamaimer Avatar answered Sep 21 '22 21:09

stamaimer