It is possible to capture an image in javascript using the MediaStream API. But in order to do so it is first necessary to instantiate a video object, then paint a frame into a canvas to get an image. But unfortunately many devices (e.g. phones) don't allow you to capture a video at the full native resolution of the device. For instance, on my phone the maximum image resolution is on the order of 4000x3000 but the maximum video resolution is a mere 1920x1080. Obviously capturing an image which is only barely 1/6th of the available resolution is unacceptable.
So how can I access the full resolution of the camera on the device?
You can't record a full-resolution picture using the MediaStream API, but you can use the Media Capture API.
The MediaStream API is able stream data from the camera, but as a video at a video resolution. This is why you can't make photos with a high resolution.
The alternative is to use the Media Capture API. It simply overrides the HTMLInput
element by adding a capture=camera
to the accept parameter. The result is that the native photo app opens to take a picture. This feature is currently (Nov 2017) only implemented in mobile browsers, so you still need WebRTC as a fallback if you need to support this feature on the desktop.
Working example
var myInput = document.getElementById('myFileInput');
function sendPic() {
var file = myInput.files[0];
// Send file here either by adding it to a `FormData` object
// and sending that via XHR, or by simply passing the file into
// the `send` method of an XHR instance.
console.log(file);
}
myInput.addEventListener('change', sendPic, false);
<input id="myFileInput" type="file" accept="image/*" capture="camera">
I feel like the current situation of the MediaStream API is to access the camera of a desktop and not to actually use it to take photos with.
来源:https://stackoverflow.com/questions/36275253/capturing-an-image-in-html5-at-full-resolution