pythonimagegoogle-app-engineblobstore

How do I get a string representation of an image before uploading?


I'm trying to intercept an image from an HTML form's input control to convert it into a byte string before processing it on the server side.

How do I intercept the file?

upload_files = self.get_uploads('file')
# Intercept here to do something different than just upload 
blob_info = upload_files[0]

How do I convert it into a byte string that can be converted back to an image later?

I'm using Python and App Engine.


Solution

  • Assume your upload control is in a form named "image" and you are using Werkzeug's FileStorage:

    img_stream = self.form.image.data
    mimetype = img_stream.content_type
    img_str = img_stream.read().encode('base64').replace('\n', '')
    
    data_uri = 'data:%s;%s,%s' % (mimetype, 'base64', img_str)
    

    Your data_uri now contains the string information you need.

    Thank you all for your helpful comments!