pythonpython-3.ximagebase64

How to convert data:image/webp;base64 content to an image


I am trying to convert the image captured via JavaScript (React.js) from HTML to an image file. I am using a Python 3 server to convert the captured data to an image.

The following is my React.js code to capture the image

var React = require ('react')
var Webcam = require('react-webcam')
var Test = React.createClass({
getInitialState:function(){
    return {};
},
capture:function(){
    var screenshot = this.refs.webcam.getScreenshot();
    this.setState({screenshot:screenshot});
    console.log("screenshot location is ",screenshot)

},
send_to_server:function(){
    RPC.execute("gold.setting","upload_webcam_blob",[this.state.screenshot],{},function(err,data) {
        if (err){
            alert(err);
            return
        }
    }.bind(this));
},
render:function(){
    console.log("apple",this.state)
    return <div>
        <Webcam ref='webcam'/>
        <button onClick={this.capture} >Capture</button>
        { this.state.screenshot ? <img src={this.state.screenshot} /> : null }
        <button onClick={this.send_to_server} >Send To Server</button>
    </div>;
},
});

module.exports= Test;

The value of the screenshot is something like the following:

data:image/webp;base64,UklGRuYmAABXRUJQVlA4INomAABwPgGdASqAAuA......

I believe it is base64 encoded data.

I send the code to the python server so I can convert to to image and save it.

Here is my python code:

def upload_webcam_blob(self,blob,context={}):
    fh = open("imageToSave.png", "wb")
    fh.write(blob.decode('base64'))
    fh.close()

The above code does create a file, but it's empty.

What am I missing? How can I convert the data to an image correctly?


Solution

  • A better idea would be to specify the screenshot format using the option screenshotFormat when using react-webcam (set it to image/png) and use this Python code to save data to a PNG file:

    from base64 import b64decode
    
    def upload_webcam_blob(self, blob, context={}):
        with open('imageToSave.png', 'wb') as fh:
            # Get only revelant data, deleting "data:image/png;base64,"
            data = blob.split(',', 1)[1]
            fh.write(b64decode(data))