Is there a way to capture a single frame from the user webcam and pass it to the server-side?
I tried using navigator.getUserMedia, which allowed me to create a LocalMediaStream object which I could pass to a video element, but there seemed to be no understandable way to get the video itself for other uses.
Anyone has any ideas?
This is a slightly round-the-houses task. You need to put the data from your stream into a video element, then put it from there into a canvas element, which will allow you to create a data URL, which can then be converted server-side into an image. (deep breath)
Your code might look a bit like this:
var stream, video, canvas, data;
navigator.getUserMedia({video: true}, function(s) {
stream = s;
});
video = document.createElement('video');
video.src = window.URL.createObjectURL(stream);
video.play();
canvas = document.createElement('canvas');
canvas.getContext('2d').drawImage(video, 0, 0, 240, 150);
data = canvas.toDataURL();
data will now be a data URL that will look a bit like this: "data:image/png;base64,iVBORw0KGgoA... (with a lot more characters at the end!). You can then use AJAX to send it to your server.
Many languages will have a way of getting information from a data URL. I've never used it, but PHP's looks particularly good. You should be able just to do this:
$image = imagecreatefrompng(substr($data, 22));
where $data is the data as it was sent from the browser. NB that I haven't tested this PHP code.
To improve the user experience, you could show the video element: the user would then be able to see the shot as it is taken. Furthermore, you could do the drawImage call as a response to an event, e.g. the user's clicking on a button. Note also that the getUserMedia function is not yet cross-browser, so you may need to do some editing to get it to work in all browsers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With