0

So to make it simple, I have a Windows.UI.Xaml.Controls.Image in my C# class that is named MyImage. I would like to convert it to byte[] so that I can store it to my database.I have no idea how to do this since the image is Windows.UI.Xaml.Controls.Image and not System.Drawing.Image so I can't do something like this:

...
 MemoryStream ms = new MemoryStream();
 imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
   return  ms.ToArray();

I would appreciate if someone could write down a simple "how to" code to do this because I just can't figure it out.

TheNewGuy
  • 49
  • 1
  • 2
  • did you check this ?http://stackoverflow.com/questions/14539005/convert-base64-string-to-image-in-c-sharp-on-windows-phone Btw.. I am not sure Gif format file is supported. – kanchirk May 29 '15 at 20:37
  • Look into the ImageSource on the Image control. Use your tools while debugging. –  May 29 '15 at 20:41

1 Answers1

0

I believe that you are using a bitmap image then

myImage = new BitmapImage(new Uri("YourImagePath", UriKind.Absolute));
MemoryStream ms = new MemoryStream();
WriteableBitmap wb = new WriteableBitmap(myImage);
wb.SaveJpeg(ms, myImage.PixelWidth, myImage.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();

This works for Windows Phone But if you are writing code for Windows Store App would suggest you to modify it.

myImage = new BitmapImage(new Uri("YourImagePath"));
RandomAccessStreamReference rasr = RandomAccessStreamReference.CreateFromUri(bitmapImage.UriSource);
var streamWithContent = await rasr.OpenReadAsync();
byte[] buffer = new byte[streamWithContent.Size];
await streamWithContent.ReadAsync(buffer.AsBuffer(), (uint)streamWithContent.Size, InputStreamOptions.None);
Jerin
  • 3,657
  • 3
  • 20
  • 45
  • But, my image is created in memory. It's not in UI. so, the step myImage = new BitmapImage(new Uri("yourimagepath")) is not valid for me. Can you help me in this? – hellodear Sep 25 '17 at 08:26
  • Could you share a code snippet of exactly how you are creating in memory. – Jerin Oct 03 '17 at 07:13
  • Simply, Image img = new Image(); img.maxDimension = 500; img.HorizontalAlignment = Stretch.None; I hope I am clear. – hellodear Oct 05 '17 at 08:48
  • Any thoughts on how to convert this Image() to writablebitmap? – hellodear Nov 26 '17 at 14:18