Take a picture from html5

Mark picture Mark · Jun 29, 2016 · Viewed 22.1k times · Source

I read a lot of ways to acquire an image from an html5 page. I'm still unsure what's the best for my needs:

  • wide support for browsers and os: at least: chrome, firefox, android default, safari
  • I don't need real-time acquisition. The user must press a button to take a picture, requesting the system camera application

There are at least three solutions :

  • <input type="file" accept="image/*;capture=camera">
  • Navigator.getUserMedia() (it seems deprecated)
  • MediaDevices.getUserMedia() (it seems experimental)

Anyway, I see a lot of examples to embed the camera into the page (w/ getUserMedia) so I don't know if I can rely only on the first method.

Answer

kanaka picture kanaka · Jun 29, 2016

Using the WebRTC getUserMedia API is going to cover all modern browsers apart from Safari: http://caniuse.com/#feat=stream

Here is an example page that uses getUserMedia to take a still picture (with a link to a page describing the code). Most getUserMedia demos show the video stream in a visible canvas area, but that's not required. You can capture an image using getUserMedia without displaying the video stream in a visible canvas.

Unfortunately, Apple has been slow to adopt WebRTC APIs so I think the file input tag is about the best your can hope for there unless you are willing to use something like Cordova. Here is a description of how to use the file input tag.

The Media Capture API is a candidate recommendation which means it is on its way to becoming a standard, however, I don't know of any browsers that implement the current W3C recommendation (using a bare capture attribute in the input tag). The <input type="file" accept="image/*"> style currently only seems to be supported by mobile browsers.

In summary, if you want to have broad browser support in the near future, you are going to need to support both methods until Apple starts supporting WebRTC APIs or until other desktop browsers start supporting the Media Capture API (or the variant with the capture attribute that is currently supported by mobile browsers).