简体   繁体   中英

Converting Windows.UI.Xaml.Controls.Image to byte[] Windows phone8.1

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM