Capture photo and save on the disk in WinJS based Windows Store App

In this post we will learn to capture a photo and save the captured photo on the disk. You can work with camera and capture a photo in the WinJS using the Windows.Media.Capture.CameraCaptureUI(). Let us start with creating the UI for the application. In the UI, we will have

  • Application bar with two buttons
  • One button to capture the photo
  • Second button is to save the photo in the Picture Library
  • Image control to preview the capture photo

Let us get it started with creating the UI. The UI mark-up will look like as follows:


<body>

    <div id="application">
        <img id="imgCaptured" />
    </div>

    <div id="AppBar" data-win-control="WinJS.UI.AppBar" data-win-options="">
        <button id="cmdSave" data-win-control="WinJS.UI.AppBarCommand" 
                data-win-options="{id:'cmdSave',label:'Save',icon:'save',section:'global',tooltip:'save'}">
        </button>
        <button id="cmdCamera" data-win-control="WinJS.UI.AppBarCommand" 
                data-win-options="{id:'cmdCamera',label:'Capture Photo',icon:'camera',section:'global',tooltip:'Capture Photo'}">
         </button>
       
    </div>
</body>


On running the application you should have a blank page with the app bar. There are two buttons to capture the photo and to save the captured photo on the disk. On the click event of the cmdCamera button we will capture a photo using following code.

 


function startCamera() {
       
            cam.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.photo).then(function (file) {
                if (file) {

                    imgCaptured.src = URL.createObjectURL(file)
                    FileToSave = file; 

                } else {
                    
                }
            }, function (err) {
                displayError(err);
            });
       
    }


Globally we have defined three variables as below,

 


     var FileToSave; 
    var cam = new Windows.Media.Capture.CameraCaptureUI();
    var folder = Windows.Storage.KnownFolders.picturesLibrary; 


Attaching click events to both buttons as shown below:

 


args.setPromise(WinJS.UI.processAll());

            document.getElementById("cmdCamera").addEventListener("click", startCamera, false);
            document.getElementById("cmdSave").addEventListener("click", takePhoto, false);

As you see on the cmdCamera button we are calling the startCamera function which is shown above. In this function by using the Media.Capture.CameraCaptureUI capturing the photo and binding that to an image control. On the other hand on the click of cmdSave we are saving the image on the disk.


function takePhoto() {
        
       
        folder.createFileAsync("photo.jpg", Windows.Storage.CreationCollisionOption.replaceExisting)
          .then(function (file) { 
              FileToSave.copyAndReplaceAsync(file);

          });
    }

The captured photo is saved in the picture library using the instance of Windows.Storage.KnownFolders.picturesLibrary. The captured image is saved with the name photo.jpg.

This is all you need to capture an image and save it in the picture library. On running application should look like follows,

image

If you are following along then find application should look like shown above. I have also used CSS to display captured image in the centre. Used CSS is given below:

 


#imgCaptured {
    
    margin-top: 200px;
    margin-left: 100px;
    width:400px;
    height: 400px; 
    margin-right:10px;
 
}

I hope this post is useful. Thanks for reading. Happy coding.

Store and Retrieve JSON data from Local storage in Windows Store App

In this tutorial step by step we will learn to save and Retrieve JSON data in Local folder of Windows Store App.

Follow following steps to save and retrieve JSON data in local storage.

Step 1

Right click on project and add Nuget package and add package of Json.NET.

image

Step 2

Let us assume that we need to store Student information in local storage. For that I have created a Student class.

 


public class Student
    {
        public string Name { get; set; }
        public string City { get; set; }
        public string Grade { get; set; }
    }


Step 3

Before saving data we need to serialize the class into JSON. We will serliaze that using JSON.net library. After serializing object into JSON we will save data in local folder of windows store application.

 


            string jsonContents = JsonConvert.SerializeObject(s);           
           StorageFolder localFolder = ApplicationData.Current.LocalFolder;
           StorageFile textFile = await localFolder.CreateFileAsync("a.txt",CreationCollisionOption.ReplaceExisting);
            using (IRandomAccessStream textStream = await textFile.OpenAsync(FileAccessMode.ReadWrite))
            {
        
                using (DataWriter textWriter = new DataWriter(textStream))
                {
                    textWriter.WriteString(jsonContents);
                    await textWriter.StoreAsync();
                }
            }

        }


S is object of class Student. We are reading student properties from various textboxes.

 


            Student s = new Student
            {
                Name =txtName.Text,
                City = txtCity.Text,
                Grade =txtGrade.Text
            };


In above code snippet,

  • We are saving file in application local folder
  • Data is saved in file a.txt
  • Opening file in asynchronous way for read write operation using IRandomAccessStream
  • Using DataWriter to write data in file

In these four steps data can be saved in local folder of Windows Store Application.

Step 4

To read JSON data back we need to first read data from local storage and then deserliaze that to object from JSON. Reading data is very simple.

  • Open local folder
  • Load file asynchronously
  • Open file asynchronously to read the streams
  • Using DataReader reading stream
  • Convert JSON to object
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
           StorageFile textFile = await localFolder.GetFileAsync("a.txt");
                using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
                {
                       
                    using (DataReader textReader = new DataReader(textStream))
                    {                                            
                        uint textLength = (uint)textStream.Size;
                        await textReader.LoadAsync(textLength);
                        string jsonContents = textReader.ReadString(textLength);                      
                        Student s = JsonConvert.DeserializeObject<Student>(jsonContents);
                        txtName1.Text = s.Name;
                        txtCity1.Text = s.City;
                        txtGrade1.Text = s.Grade;
                       
                    }
                }

In above code snippet,

  • We are opening local folder
  • Opening file asynchronously
  • Reading stream in IRandonAccessStream
  • Reading data using DataReader
  • DeSeralizing JSON to object using JsonConver

By following above steps you can save and retrieve data in local folder of Windows Store application. I hope you find this article useful.

Thanks to Student created Windows 8 App of my Blog

I am very pleased to write here that one student Akrita Agarwal has shown her love to my blog and voluntarily created Windows 8 Application of my blog. I am very touched by this kind effort. You can get that app from App Store from here


Link to download Application from Store


   

This is two column application. You can browse blog posts on selecting a particular blog post from left. There is feature of searching a blog post and about author as well.

   

 

This may not be the best application but we are celebrating proactive step taked by a student to create an Application for Windows Store here.

Thanks to Akrita and their friends.