0

I am trying to save an existing image (inside a button in my app) to byte[] then save it to SQLite database. I know how to use FileOpenPicker to load and convert to IRandomAccessStream, and I know how to save to database but I can't figure our how to convert an existing image to byte array in metro apps/windows UI.

I have searched a lot but found mainly examples with FileOpenPicker or using memory stream which doesn't seem to work with metro apps.

thank you.

Rune FS
  • 21,497
  • 7
  • 62
  • 96
user1939246
  • 11
  • 1
  • 3

1 Answers1

0

You can use a Datareader as

    var file = await new FileOpenPicker().PickSingleFileAsync();
    var fStream = await file.OpenAsync(FileAccessMode.Read);

    var reader = new DataReader(fStream.GetInputStreamAt(0));
    var bytes = new byte[fStream.Size];
    await reader.LoadAsync((uint)fStream.Size);
    reader.ReadBytes(bytes);

Finally you can save bytes to database.

One more example here Reading a StorageFile to a byte array in C#

Added Edit

WinRT you will need to use http://writeablebitmapex.codeplex.com/

WinRT Loading an Image into a Byte array

Quoting..

Basically you need to load the image into a WriteableBitmap, then access its pixel buffer by calling PixelBuffer.AsStream().

Community
  • 1
  • 1
Amitd
  • 4,769
  • 8
  • 56
  • 82
  • the image is inside a button in my app. I don't need to use FileOpenPicker. I need to convert that image to byte array. – user1939246 Mar 17 '13 at 16:56
  • Is it possible to share some code/xaml ? btw you can examine button's bacground property to get an bitmap image which you can convert to byte array – Amitd Mar 17 '13 at 17:56
  • 'foreach (var btn in ButtonsCollection) { var bmp = btn.Image; ////////////////////// // I need to convert bmp to IRandomAccessStream and I am stuck ////////////////////// var reader = new DataReader(stream.GetInputStreamAt(0));// var bytes = new byte[stream.Size]; await reader.LoadAsync((uint)stream.Size); reader.ReadBytes(bytes); }' – user1939246 Mar 17 '13 at 18:37
  • Thanks Amitd but I am working with c# windows 8 Metro apps and there is no bitmapencoder frames. – user1939246 Mar 17 '13 at 19:20
  • Sorry my bad.. Edited my answer – Amitd Mar 17 '13 at 20:24