How to save WriteableBitmap Image to Storage File in Windows Phone 8.1 RT/Windows 10 ?
To convert a WriteableBitmap to Storage File first you need Encode the Image in the right way so that it won't turn out to be blank image.
Where wb is your WriteableBitmap Image, the second parameter is which type of format you want to save as. you can choose different available formats Tiff, Jpeg, PNG, BMP etc.., depending on your selection you can select the format which you want to encode and save.
- StorageFile filePath = await WriteableBitmapToStorageFile(wb, FileFormat.Jpeg);
- private async Task < StorageFile > WriteableBitmapToStorageFile(WriteableBitmap WB, FileFormat fileFormat)
- {
- string FileName = "YourFile.";
- Guid BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
- switch (fileFormat)
- {
- case FileFormat.Jpeg:
- FileName += "jpeg";
- BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
- break;
- case FileFormat.Png:
- FileName += "png";
- BitmapEncoderGuid = BitmapEncoder.PngEncoderId;
- break;
- case FileFormat.Bmp:
- FileName += "bmp";
- BitmapEncoderGuid = BitmapEncoder.BmpEncoderId;
- break;
- case FileFormat.Tiff:
- FileName += "tiff";
- BitmapEncoderGuid = BitmapEncoder.TiffEncoderId;
- break;
- case FileFormat.Gif:
- FileName += "gif";
- BitmapEncoderGuid = BitmapEncoder.GifEncoderId;
- break;
- }
- var file = await Windows.Storage.ApplicationData.Current.TemporaryFolder.CreateFileAsync(FileName, CreationCollisionOption.GenerateUniqueName);
- using(IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
- {
- BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoderGuid, stream);
- Stream pixelStream = WB.PixelBuffer.AsStream();
- byte[] pixels = new byte[pixelStream.Length];
- await pixelStream.ReadAsync(pixels, 0, pixels.Length);
- encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint) WB.PixelWidth, (uint) WB.PixelHeight,
- 96.0,
- 96.0,
- pixels);
- await encoder.FlushAsync();
- }
- return file;
- }
- private enum FileFormat
- {
- Jpeg,
- Png,
- Bmp,
- Tiff,
- Gif
- }
And you can set this saved file path as Image source like the following:
-
- BitmapImage bmpImage = new BitmapImage(new Uri(file.Path));
- Myimage.Source=bmpImage ;
- <Image x:Name="MyImage" strech="Uniform"/>