Convert image to byte array in windows 8,win RT

Windows RT has  very limited imaging capabilities.And there are very few examples on how to convert an image into a byte array and how to save it in a disk.Here is the code for doing that

StorageFile outputFile = await savePicker.PickSaveFileAsync();
using (IRandomAccessStream outputStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
outputStream.Size = 0;
Guid encoderId = BitmapEncoder.BmpEncoderId;
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, outputStream);
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream1);
 PixelDataProvider pixelProvider = await decoder.GetPixelDataAsync();
 byte[] pixels = pixelProvider.DetachPixelData();
  await encoder.FlushAsync();

First we use the file picker ,which is like the savefiledialog where the user enters the details of the file , the user wants to save.

Then we use the IRandomAccessStream  to open the output file for writing.Now its important to set the size of the outputstream to zero because the user might select an existing file.Then we use the GUID encoder to set the encoding we want.

You have option for PNG,BMP and JPG . So you can convert your image into any of the 3 types.

Next we create a BitmapEncoder ,When you create a BitmapEncoder, it provides access to data on the container and the first frame.

The BitmapDecoder class implements IBitmapFrame. It provides access to container data as well as data from the first frame. This allows applications to accomplish most common scenarios without needing to retrieve a separate BitmapFrame.

WinRT introduces PixelDataProvider class for ease of getting information on pixels.From there we can get the byte array of the image.Now to save the image we simply call encoder.FlushAsync(); on the encoder.This is how you can save an image from the stream


One response to “Convert image to byte array in windows 8,win RT

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s