Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WPF

How to Save and Retrieve Picture in Format JSON

4.82/5 (3 votes)
5 Aug 2014CPOL 50.4K  
We always wonder how we can store pictures in database

Introduction

The easiest way to do it is simply convert the pic to Byte[], then store it on Format JSON as local database, and we do the opposite to retrieve it.

Background

You need to install JSON.NET on nuget package.

Using the Code

For example, we browse a picture and we want to store it. So the first thing we do is convert the file on Byte[] (fileBytes):

C++
if (file != null)
           {
               using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
               {
                   fileBytes = new byte[stream.Size];
                   using (DataReader reader = new DataReader(stream))
                   {
                       await reader.LoadAsync((uint)stream.Size);
                       reader.ReadBytes(fileBytes);
                   }
               }

               using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
               {

                   using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
                   {
                       writer.WriteBytes((byte[])fileBytes);
                       writer.StoreAsync().GetResults();
                   }

           }

After that, we add a class which has a property of type Byte[], for example:

C++
public class Images
   {
       public byte[] Imagess { get; set; }
       public int Num { get; set; }
   }

We create a List of Images and then add all fileBytes converted.

C++
listebytes.Add(new Images() { Imagess = fileBytes,Num= listebytes.Count });

After we create a List of Bytes, then we call the function that saves this List in Format JSON. The function needs the file name of Json and the List of Bytes to store it:

C++
public string imgfile= "Image.json";

public async void SaveImage()
       {
           string jsonContents = JsonConvert.SerializeObject(listebytes);
           // Get the app data folder and create or replace the file we are storing the JSON in.
           StorageFolder localFolder = ApplicationData.Current.LocalFolder;
           StorageFile textFile = await localFolder.CreateFileAsync(imgfile,
                                        CreationCollisionOption.ReplaceExisting);
           // Open the file...
           using (IRandomAccessStream textStream = await textFile.OpenAsync(FileAccessMode.ReadWrite))
           {
               // write the JSON string!
               using (DataWriter textWriter = new DataWriter(textStream))
               {
                   textWriter.WriteString(jsonContents);
                   await textWriter.StoreAsync();
               }
           }
       }

We can also retrieve the JSON to show our Images so we call a function that loads our JSON:

C++
private async void LoadImage()
       {
           StorageFolder localFolder = ApplicationData.Current.LocalFolder;
           string ch = localFolder.Path;


               // Getting JSON from file if it exists, or file not found exception if it does not
               textFile = await localFolder.GetFileAsync(imgfile);
               using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
               {
                   // Read text stream
                   using (DataReader textReader = new DataReader(textStream))
                   {
                       //get size
                       uint textLength = (uint)textStream.Size;
                       await textReader.LoadAsync(textLength);
                       // read it
                       jsonContents = textReader.ReadString(textLength);
                       // deserialize back to our product!
                       listebytes = JsonConvert.DeserializeObject<IList<Images>>
                       (jsonContents) as List<Images>;

                       // and show it
                   }
               }
       }

After getting List of Bytes we converted to BitmapImage to show them, we add the following code inside the Function of LoadImage:

C++
  foreach (var item in <code>listebytes)
         {
             Stream stream = new MemoryStream(item.Imagess);
             WriteableBitmap writimage = new WriteableBitmap(1, 1);
             Windows.Graphics.Imaging.BitmapPixelFormat format =
             Windows.Graphics.Imaging.BitmapPixelFormat.Unknown;

     writimage = await WriteableBitmapExtensions.FromStream(writimage, stream, format);

//add these image to a List of Images
         }

History

To store Image, we should code step by step and follow the logic to do it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)