7

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?

Michael
  • 9,060
  • 14
  • 61
  • 123

1 Answers1

9

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.

oligofren
  • 20,744
  • 16
  • 93
  • 180
Tom
  • 869
  • 6
  • 25
  • 1
    For the time being, capture=camera works for me! thanks! – Michael Apr 07 '16 at 15:47
  • FYI - this input type='file' will prompt for a filename in a Windows PC browser, but on a mobile device it all show the camera with the camera options (checked on ios ipad and android mobile), – user1432181 Jul 24 '23 at 15:52