Save And Retrieve Image File From Stream To Local Storage In Windows Phone 8.1 Runtime Apps

To save and retrieve image file from a stream to local storage in Windows Phone 8.1 Runtime Apps, firstly you need to set the stream to WritableBitmapImage like the following:

  1. var wbm = new WriteableBitmap(600, 800);  
  2. await wbm.SetSourceAsync(stream);  
Next, here's the code for saving this writable Bitmap Image.
  1. StorageFolder folder = ApplicationData.Current.LocalFolder;  
  2. if (folder != null)   
  3. {  
  4.     StorageFile file = await folder.CreateFileAsync("imagefile" + ".jpg", CreationCollisionOption.ReplaceExisting);  
  5.     using(var storageStream = await file.OpenAsync(FileAccessMode.ReadWrite))   
  6.     {  
  7.         var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, storageStream);  
  8.         var pixelStream = wbm.PixelBuffer.AsStream();  
  9.         var pixels = new byte[pixelStream.Length];  
  10.         await pixelStream.ReadAsync(pixels, 0, pixels.Length);  
  11.         encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint) wbm.PixelWidth, (uint) wbm.PixelHeight, 48, 48, pixels);  
  12.         await encoder.FlushAsync();  
  13.     }  
  14. }
To Retrieve this Image Again
  1. string fileName = "imagefile.jpg";  
  2. StorageFolder myfolder = ApplicationData.Current.LocalFolder;  
  3. BitmapImage bitmapImage = new BitmapImage();  
  4. StorageFile file = await myfolder.GetFileAsync(fileName);  
  5. var image = await Windows.Storage.FileIO.ReadBufferAsync(file);  
  6. Uri uri = new Uri(file.Path);  
  7. BitmapImage img = new BitmapImage(new Uri(file.Path));  
  8. myimage.Source = img;  
Here my image is an image control like the following code snippet:
  1. <Image x:Name="myimage" Stretch="Fill" HorizontalAlignment="Left" VerticalAlignment="Top"/>  
It's done. Comment below for any doubt.
Ebook Download
View all
Learn
View all