Search code examples
c#windows-phone-8.1arrays

Convert BitmapImage to byte[]


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.


Solution

  • 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();
            }
        }