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