I have problem with converting BitmapImage to byte[]. I tried a lot of solutions and nothing works, every time i get different errors.
For example i found nice solutions but it also doesn't work. What's wrong with it?
I'm using Windows Phone 8.1.
public static byte[] ImageToBytes(BitmapImage img)
{
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap(img);
System.Windows.Media.Imaging.Extensions.SaveJpeg(btmMap, ms, img.PixelWidth, img.PixelHeight, 0, 100);
img = null;
return ms.ToArray();
}
}
this was taken from here: Convert Bitmap Image to byte array (Windows phone 8)
There is no argument given that corresponds to the required formal
parameter 'pixelHeight' of 'WriteableBitmap.WriteableBitmap(int, int)'
The type or namespace name 'Extensions' does not exist in the
namespace 'System.Windows.Media.Imaging' (are you missing an assembly
reference?)
or if somebody has got another idea how to convert it, please post it. Thanks a lot for any help!
I also tried this: BitmapImage to byte[]
but there was problem with usings
'BitmapImage' is an ambiguous reference between 'System.Windows.Media.Imaging.BitmapImage' and 'Windows.UI.Xaml.Media.Imaging.BitmapImage'
so I used "BitmapEncoder" but it doesn't have method like Save and Frame.
I think that it can't be done on this platform. I change my project to Windows Phone Silverlight/8.0 and there is working everything.
public static BitmapImage BytesToImage(byte[] bytes)
{
BitmapImage bitmapImage = new BitmapImage();
try
{
using (MemoryStream ms = new MemoryStream(bytes))
{
bitmapImage.SetSource(ms);
return bitmapImage;
}
}
finally { bitmapImage = null; }
}
public static byte[] ImageToBytes(BitmapImage img)
{
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap(img);
System.Windows.Media.Imaging.Extensions.SaveJpeg(btmMap, ms, img.PixelWidth, img.PixelHeight, 0, 100);
img = null;
return ms.ToArray();
}
}
see the below link it might help
https://social.msdn.microsoft.com/Forums/en-US/713c0ed1-d979-43ef-8857-bbe0b35576a9/windows-8-how-to-convert-bitmapimage-into-byte?forum=winappswithcsharp
Have you tried
MemoryStream ms = new MemoryStream();
WriteableBitmap wb = new WriteableBitmap(myImage);
wb.SaveJpeg(ms, myImage.PixelWidth, myImage.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();
You can also use extension method here
public static class MyExtensions
{
public static Byte[] ByteFromImage(this System.Windows.Media.Imaging.BitmapImage imageSource)
{
Stream stream = imageSource.StreamSource;
Byte[] imagebyte = null;
if (stream != null && stream.Length > 0)
{
using (BinaryReader br = new BinaryReader(stream))
{
imagebyte = br.ReadBytes((Int32)stream.Length);
}
}
return imagebyte;
}
}
and then call
System.Windows.Media.Imaging.BitmapImage myImage = new System.Windows.Media.Imaging.BitmapImage();
byte[] imageBytes = myImage.ByteFromImage();