Invoking Camera Using WinJS


Couple of days back, I got a task to capture image of an user. The image area is very limited in size. The user has to crop the image as per the required size and area to display. Before start worrying about the same, I was glad to see the features provided by WinJS.

We can use Windows.Media.Capture.CameraCaptureUI to invoke the camera and capture image. This not only shows the camera UI on screen but also displays the cropping options along with pixel adjustment and timer options.

Below is just a simple example of how it works.


    <input type="button" id="btnOpenCamera" value="Open Camera" />
    <br />
    <img src="#" id="imgCapture" alt="Caputured Image" style="display:none" />

We have added a button to open the camera and an image control to display the captured image on screen.

JavaScript PART:-

app.onready = function (args) {
        var cameraButton = document.getElementById("btnOpenCamera");
        cameraButton.addEventListener("click", function () {
            var cam = new Windows.Media.Capture.CameraCaptureUI();
                function (file) {
                    var capturedImage = document.getElementById("imgCapture");
                    if (file)
                    { = "";
                       capturedImage.src = URL.createObjectURL(file);

In the JS file, which meant to handle the above Html UI, we tried to locate the button from the DOM. Then added the click event handler to the button. It will get fired when button gets clicked.

We created an object from the CameraCaptureUI class to deal with the camera screen and get our desired output. In the very next line, on invoking the captureFileAsync method of the cameraCaptureUI class, we will get the camera UI appear on  screen.

We can take picture out of that. After taking the picture, it shows the option to accept the image as it is or to crop the same  as per the need. On accepting the cropped image, it  returns the image as a blob data.To display this blob data in the image control, we tried to create an object URL and assign the same to the image control and made the image control visible on screen.


The output is hard to display on screen shots since this requires a camera invoke. The best way to test this example, is to try to debug the same from a surface tablet. This can be done by using debug in the Remote Machine option or can create an app and deploy the same in a surface tablet.

Written By: Nirmal Hota, X-platform Mobile Lead, Mindfire Solutions

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s