QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads Create a Camera App using Intel XDK

Create a Camera App using Intel XDK

intelxdk-camera-app

This post is a part 30 of Intel XDK Complete Tutorial post series.

In this tutorial I will introduce you to Intel XDK camera API. We will be creating an sample application which lets you take a picture using camera or imports picture from photo library. It also displays the image and uploads the image to server.

Let’s get started

Including Camera and File Plugins

Make sure you include Intel XDK camera and file plugins in your app.

Capture

Basic Template

This is the basic template of the app

<!DOCTYPE html>
<html>
<head>
    <title>Blank Hybrid App Project Template</title>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">

    <style>
        @-ms-viewport { width: 100vw ; zoom: 100% ; }                          
        @viewport { width: 100vw ; zoom: 100% ; }
        @-ms-viewport { user-zoom: fixed ; }                                    
        @viewport { user-zoom: fixed ; }
    </style>

    <script src="lib/ft/fastclick.js"></script>

    <link rel="stylesheet" href="css/app.css">
</head>
<body>
    <img src="" id="picture" width="200" height="150" />
    <progress min="0" max="100" id="progress"></progress><br>
    <button onclick="captureCamera();">Take a Picture</button>
    <button onclick="importLibrary();">Import from Library</button>
   
    <script src="intelxdk.js"></script>        
    <script src="cordova.js"></script>          
    <script src="xhr.js"></script>              

    <script src="js/app.js"></script>
    <script src="js/init-app.js"></script>
    <script src="js/init-dev.js"></script>
</body>
</html>

Capturing or Importing Image

Here is the JavaScript code to capture or import image into application storage when respective buttons are clicked

        function captureCamera()
        {
            /*this function opens default camera app and captures a picture. It stores the captured image in application storage. Parameters:
            1. Quality 0-100
            2. Should stores the picture in photo library of phone also or not
            3. Image format png or jpg
            */

            intel.xdk.camera.takePicture(10,true,"png");
        }
       
        function importLibrary()
        {
            //this function opens default photo library of phone and imports a image into application storage.
            intel.xdk.camera.importPicture();
        }

Handing Success, Busy and Cancel Events

Event is fired based on your action on native camera or photo library application when they are opened. Here is the JavaScript code to handle the events.

//fired when picture is successfully captured using camera or imported from photo library.
        document.addEventListener("intel.xdk.camera.picture.add",function(event){
            alert("Picture added to application local storage");
        });
       
        //fired if camera is in use by another app
        document.addEventListener("intel.xdk.camera.picture.busy",function(){
            alert("Camera is already in use");
        });
       
        //fired when user clicks cancel instead of capturing an image or importing.
        document.addEventListener("intel.xdk.camera.picture.cancel",function(){
            alert("You pressed the cancel button");
        });

Displaying Picture

We can display the image once we have it on our application local storage. Every image inside application local storage gets a unique name. Image file name is the image identifier.

        document.addEventListener("intel.xdk.camera.picture.add",function(event){
            //picture name
            var name = event.filename;
           
            //absolute URL of the image
            var url = intel.xdk.camera.getPictureURL(name);
           
            //dislay the image
            document.getElementById("picture").setAttribute("src", url);
        });

Uploading Image to Server

We can upload the image once we have it on our application local storage. We can upload it using Intel XDK File Upload API.

        //fired when picture is successfully captured using camera or imported from photo library.
        document.addEventListener("intel.xdk.camera.picture.add",function(event){
            //picture name
            var name = event.filename;
           
            //absolute URL of the image
            var url = intel.xdk.camera.getPictureURL(name);
           
            //upload the image to server
            intel.xdk.file.uploadToServer(url,"http://labs.qnimate.com/demo/index.php", "", "image/png", "updateUploadProgress");
        });


    document.addEventListener("intel.xdk.file.upload.busy",uploadBusy);
    document.addEventListener("intel.xdk.file.upload",uploadComplete);
    document.addEventListener("intel.xdk.file.upload.cancel",uploadCancelled);

    function uploadBusy(evt)
    {
       alert("Sorry, a file is already being uploaded");
    }

    function uploadComplete(evt)
    {
       if(evt.success==true)
       {
          alert("File "+evt.localURL+" was uploaded");
       }
       else {
          alert("Error uploading file "+evt.message);
       }
    }

    function uploadCancelled(evt)
    {
        alert("File upload was cancelled "+evt.localURL);
    }

Handling Uploads on Server

This is a sample PHP script to handle uploads on server

<?php
    set_time_limit(0);
    move_uploaded_file($_FILES["Filedata"]["tmp_name"], $_FILES["Filedata"]["name"]);
?>

Complete App Source code

Here is the code for the complete app

<!DOCTYPE html>
<html>
<head>
    <title>Blank Hybrid App Project Template</title>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">

    <style>
        @-ms-viewport { width: 100vw ; zoom: 100% ; }                          
        @viewport { width: 100vw ; zoom: 100% ; }
        @-ms-viewport { user-zoom: fixed ; }                                    
        @viewport { user-zoom: fixed ; }
    </style>

    <script src="lib/ft/fastclick.js"></script>

    <link rel="stylesheet" href="css/app.css">
</head>
<body>
    <img src="" id="picture" width="200" height="150" />
    <progress min="0" max="100" id="progress"></progress><br>
    <button onclick="captureCamera();">Take a Picture</button>
    <button onclick="importLibrary();">Import from Library</button>
   
    <script src="intelxdk.js"></script>        
    <script src="cordova.js"></script>          
    <script src="xhr.js"></script>              

    <script src="js/app.js"></script>
    <script src="js/init-app.js"></script>
    <script src="js/init-dev.js"></script>
   
    <script>
        function captureCamera()
        {
            intel.xdk.camera.takePicture(10,true,"png");
        }
       
        function importLibrary()
        {
            intel.xdk.camera.importPicture();
        }
       
        document.addEventListener("intel.xdk.camera.picture.add",function(event){
            var name = event.filename;
            var url = intel.xdk.camera.getPictureURL(name);
            document.getElementById("picture").setAttribute("src", url);
            intel.xdk.file.uploadToServer(url,"http://labs.qnimate.com/demo/index.php", "", "image/png", "updateUploadProgress");
        });
       
        document.addEventListener("intel.xdk.camera.picture.busy",function(){
            alert("Camera is already in use");
        });
       
        document.addEventListener("intel.xdk.camera.picture.cancel",function(){
            alert("You pressed the cancel button");
        });
       
        function updateUploadProgress(bytesSent,totalBytes)
        {
           if(totalBytes>0)
                currentProgress=(bytesSent/totalBytes)*100;
            document.getElementById("progress").setAttribute("value", currentProgress);
        }

        document.addEventListener("intel.xdk.file.upload.busy",uploadBusy);
        document.addEventListener("intel.xdk.file.upload",uploadComplete);
        document.addEventListener("intel.xdk.file.upload.cancel",uploadCancelled);

        function uploadBusy(evt)
        {
           alert("Sorry, a file is already being uploaded");
        }

        function uploadComplete(evt)
        {
           if(evt.success==true)
           {
              alert("File "+evt.localURL+" was uploaded");
           }
           else {
              alert("Error uploading file "+evt.message);
           }
        }

        function uploadCancelled(evt)
        {
            alert("File upload was cancelled "+evt.localURL);
        }  
    </script>
</body>
</html>

IMG_0539IMG_0540IMG_0542

Its not all about Intel XDK camera API. You can do many more things.

Displaying all Images

This is the code to display all captured and imported images into app storage

//returns a array of strings where each string represent name of a image file.
var arrPictureList = intel.xdk.camera.getPictureList();
for (var x=0;x<arrPictureList.length;x++)
{
    var name = arrPictureList[x];
    var url = intel.xdk.camera.getPictureURL(name);
}

Deleting Images

To delete a image you just need the image file name. Here is the code to remove all images

var arrPictureList = intel.xdk.camera.getPictureList();
for (var x=0;x<arrPictureList.length;x++)
{
    var name = arrPictureList[x];
    //this function is used to delete a image file.
    intel.xdk.camera.deletePicture(name);
}

//this is fired after every attempt to delete an image.
document.addEventListener("intel.xdk.camera.picture.remove",onRemove);

function onRemove(evt)
{
    if(evt.success==true)
    {
        alert(evt.filename + " has been removed from the application storage");
    }
    else
    {
        alert(evt.filename + " has been failed to remove from application storage");
    }
}

Building app Binary

While building app binary for Android make sure you set permission to access user’s camera

Screen Shot 2015-01-01 at 2.54.26 pm

Dec 2, 2014Narayan Prusty
Increase PHP Script Execution TimeAccessing User Phone Contacts using Intel XDK
Comments: 20
  1. friv
    4 years ago

    Your great article. Hopefully there will be more posts kizi

    ReplyCancel
  2. friv6
    4 years ago

    Thanks forums, forums are very useful and meaningful, everyone playing the game is on the following link
    http://www.friv6edge.com/

    ReplyCancel
  3. friv2
    4 years ago

    Thanks forums, forums are very useful and meaningful, everyone playing the game is on the following link
    http://www.friv2.city/

    ReplyCancel
  4. Mohan
    5 years ago

    Hey Narayan, this is all a crap OMG … have you tested this app at least once ?!

    ReplyCancel
  5. Friv2
    5 years ago

    It shows “ReferenceError: intel is not defined”. What have I missed?

    ReplyCancel
    • Friv2
      5 years ago

      https://software.intel.com/en-us/xdk/docs/intel-xdk-api-cordova-plugin-methods-properties-events

      It’s says intel.xdk api is retried.

      ReplyCancel
  6. huda
    5 years ago

    how to shoot photos?

    ReplyCancel
    • huda
      5 years ago

      please , help me

      ReplyCancel
  7. andi
    6 years ago

    Hi, how to close camera after take a photo and save image ?

    ReplyCancel
  8. Nidhin
    6 years ago

    How to create a folder to save the captured images as well as how to save the image name using timestamp instead of saving it as test.jpg.Googled a lot but didn’t find any good solutions.

    ReplyCancel
  9. adittya
    6 years ago

    hai..
    thanks befor, it help me alot with intel xdk.
    But, how to prevent duplicate file?

    ReplyCancel
  10. mike
    6 years ago

    Hi, I am having problem with this line:

    intel.xdk.file.uploadToServer(url,”http://labs.qnimate.com/demo/index.php”, “”, “image/png”, “updateUploadProgress”);
    });

    Im using a localhost via xampp. What will i put in the 2nd parameter(i have no index.php).

    ReplyCancel
  11. Veselov
    6 years ago

    Very detailed description/
    Thank you

    ReplyCancel
  12. Emre
    6 years ago

    Hi,
    Do you know a solution about sharing photo on instagram ?

    Thanks

    ReplyCancel
  13. Nilesh Pathade
    6 years ago

    // There I am using intel xdk.for capture picture by camera it takes picture but image name takes by default “test.jpg” every time . and 2nd picture override so is there any solution for saving image with different name.
    function capturePhoto() {
    intel.xdk.camera.takePicture(50,true,”jpg”);
    }
    document.addEventListener(“intel.xdk.camera.picture.add”,function(event){
    if (event.success == true)
    {
    var name = event.filename;
    var url = intel.xdk.camera.getPictureURL(name);
    }
    }

    ReplyCancel
  14. Ashish
    7 years ago

    please help me out to convert the image into base64 string in xdk.

    ReplyCancel
  15. Ninja
    7 years ago

    Not working,,, this sites are full of error… I think the author just copy-paste to others without testing it!!!

    ReplyCancel
  16. reytabs
    7 years ago

    it doesn’t work. .can u give a full source of this. .

    ReplyCancel
  17. reytabs
    7 years ago

    its ok if i build in cordova?

    ReplyCancel
    • Judith
      5 years ago

      Does the Bioptimax Acai Weight Loss Pill Work?I got a little brochure in the mail that is guanrateeing that you will loose 20 -50 pounds. Its called the BiOptimax ACAI Ultimate Weight-Loss Formula.Has anybody ever heard of it or used it? Does it work?

      ReplyCancel

Leave a Reply Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

Image7 years ago 20 Comments Cordova
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
  • Including Camera and File Plugins
  • Basic Template
  • Capturing or Importing Image
  • Handing Success, Busy and Cancel Events
  • Displaying Picture
  • Uploading Image to Server
  • Handling Uploads on Server
  • Complete App Source code
  • Displaying all Images
  • Deleting Images
  • Building app Binary
Related Articles
  • Accessing User Phone Contacts using Intel XDK
  • Create a Feed Reader App using Intel XDK
  • Downloading Files and Showing Progress using Intel XDK
  • Create a Password Manager App using Intel XDK
  • Uploading Files and Showing Progress using Intel XDK
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license