Using the Camera from Mobile Web

In the early days of mobile web, it was not possible to access the camera from a web page. While Android added the functionality a while ago in Honeycomb, it seems to have quietly slipped in to iOS in 6.0. So now, the majority of smartphone users can use the camera from a web site.

The HTML code is to access the camera is surprisingly simple:

<input type='file' accept="image/*" capture="camera" onchange="previewImage(this);" />

The accept and capture attributes do all the work. In my example I’ve also added an onchange handler to add a preview of the image to the HTML page:

<div style="height: 400px; width:200px"><img id="preview" src="" alt="your image here" /></div>
<script type="text/javascript">
     $('#preview').on('load',function() {
         var css;
         var ratio=$(this).width() / $(this).height();
         var pratio=$(this).parent().width() / $(this).parent().height();
         if (ratio<pratio) {
             css={width:'auto', height:'100%'};
         } else {
             css={width:'100%', height:'auto'};
         }
         $(this).css(css);
     });
     function previewImage(input) {
         if (input.files && input.files[0]) {
             var reader = new FileReader();
             reader.onload = function (e) {
                 $('#preview').attr('src',e.target.result)
             };
             reader.readAsDataURL(input.files[0]);
         }
      }
</script>

Try it out

Interestingly, on iOS the photo stays in memory and is not persisted to the device. On Android, the photo is automatically persisted to the gallery. I suspect this is for memory management.

I have tested this code successfully on the following platforms:

  • Android 3.0+ browser
  • Chrome on Android
  • Mobile Safari on iOS6+
  • BlackBerry 10

The only large group of smartphone users left out in the cold are Android users still on Gingerbread.

I tested this code on WP8, and it didn’t work. There may be a work around, but I haven’t had a chance to work that out yet.