Sunday, April 26, 2015

How to Convert BitmapImage to Storage File in Windows Phone 8.1 Win RT

BitmapImage to Storage File conversion requires following steps.
  1. BitmapImage to byte array conversion.
  2. Creation of temporary StorageFile.
  3. Writing byte array data on empty storage file.
BitmapImage to byte array conversion

BitmapImage bitmap = ImageBoxPreview.Source as BitmapImage;

RandomAccessStreamReference rasr = RandomAccessStreamReference.CreateFromUri(bitmap.UriSource);

var streamWithContent = await rasr.OpenReadAsync();

byte[] buffer = new byte[streamWithContent.Size];

await streamWithContent.ReadAsync(buffer.AsBuffer(),(uint)streamWithContent.Size, InputStreamOptions.None);


Creation of temporary StorageFile

StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("temp.jpeg", CreationCollisionOption.ReplaceExisting);


Writing byte array data on empty storage file

using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
      using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
      {
               using (DataWriter dataWriter = new DataWriter(outputStream))
               {
                      dataWriter.WriteBytes(buffer);
                      await dataWriter.StoreAsync(); // 
                      dataWriter.DetachStream();
               }
               // write data on the empty file:
               outputStream.FlushAsync();
       }
        fileStream.FlushAsync();
}



Complete code will be:


Convert BitmapImage  to Storage File in Windows Phone 8.1 Win RT

Convert BitmapImage to Storage File in Windows Phone 8.1 Win RT.

3 comments:

  1. Great post! The fact that you means someone is reading and liking it! Congrats!That’s great advice.
    Graphic Design | Rochester Ny Graphic Design

    ReplyDelete
  2. Hi man, I need convert a stream to IStorageItem... Can you help me please? see my current code => https://gist.github.com/jdnichollsc/619f9db2c3e61667ea35

    ReplyDelete
  3. I’m really enjoying the design and layout of your blog. It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire out a designer to create your theme? Great work! Thanks for sharing with us how to convert BitmapImage to Storage File in Windows Phone. Carry on :)

    Best Kids Website Design for Pediatricians Dentists in New York.

    ReplyDelete