Capturing Image Using Camera In Windows 10 Universal App Using JavaScript

Let’s see the steps.

Create new windows 10 universal app using javascript. For creating a new Windows 10 universal project, refer to the following:

We need to enable the capability “Webcam" in the Package.appx manifest file as in the following image.

file

Next we need to add a button to capture Image and an Image control to show the captured image.

Go to default.html page and write the following code.

  1. <input type="button" id="btnCapture" value="Capture"  
  2. onclick="captureImage()" />  
  3. <img id="imgCapture" src="" width="100px" height="100px" />  
Now go to default.js file and add the following code on capture button click event to capture the image using camera.
  1. var page = WinJS.UI.Pages.define("default.html",  
  2. {  
  3. ready: function (element, options) {  
  4. document.getElementById("btnCapture").addEventListener("click", captureImage, false);  
  5. },  
  6. });  
  7.   
  8. function captureImage() {  
  9.   
  10. var cam = Windows.Media.Capture.CameraCaptureUI();  
  11. cam.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.photo)  
  12. .done(function (data) {  
  13. if (data) {  
  14. document.getElementById('imgCapture').src  
  15. = window.URL.createObjectURL(data);  
  16. }  
  17. }  
  18. , error);  
  19. }  
  20. function error() {  
  21. alert('Error');  
  22. }  
The ‘CameraCaptureUI’ class is used to capture photo or video from the camera. The CaptureFileAsync() method creates an object and displays the dialog box to capture a photo or video. ‘Done’ represents the completion of the async operation which here in case displays the captured photo in the <img> tag.

Now run the app and output can be seen like the following screen:

output

For more information on Windows 10 UWP, refer to my e-book: 
Read more articles on Windows 10:

Up Next
    Ebook Download
    View all
    Learn
    View all