This project is read-only.

Can't convert it Bitmap

Dec 12, 2010 at 10:09 AM


I'm using the code below to convert the Bitmap to byte[]. I got this code from WriteableBitmapExtensions of your library.

 public byte[] ToBitArray(BitmapImage bitmapImage)
            var bitmap = new WriteableBitmap(bitmapImage);

            int offset = 0, count = bitmap.Pixels.Length, SizeOfArgb = 4;

            int len = count * SizeOfArgb;
            byte[] result = new byte[len]; // ARGB
            Buffer.BlockCopy(bitmap.Pixels, offset, result, 0, len);

            return result;

The problem is that I can't convert those bytes back to Bitmap. 

 private BitmapImage ToBitmapImage(byte[] bytes)
            using (var stream = new MemoryStream(bytes))
                BitmapImage img = new BitmapImage();
                return img;


I'm getting this error. Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED)) .. Any idea? 

Dec 12, 2010 at 12:20 PM

BitmapImage SetSource expects a JPEG stream, you are passing a raw byte array. See how the methods are implemented in this library or just use them. You should also check out the WriteableBitmap and BitmapImage base class, maybe you can alter your interfaces.

- Rene

Dec 12, 2010 at 2:42 PM

The image that I passed to "ToByteArray" is JPG ... You mean, the output that I got from ToByteArray is raw? So, I need to encode those bytes to JPG format again? 

I didn't see any function that can convert BitmapImage to Byte[] vice versa in your library..  I don't need other functionality as well .. that's why im trying to get that conversion functionality only.. 


Dec 12, 2010 at 8:42 PM

Yes, ToByteArray returns the ARGB pixesls as byte array. Look up the WriteableBitmap Pixels property and the Buffer BlockCopy at MSDN to see want they mean. A JPEG encoding always means a loss in quality. It's a lossy compression. Don't do it.

BitmapImage does not work very well here. Also, the library is called WriteableBitmapEx.

Why don't you want to use the WriteableBitmap in your code? Please also note, BitmapImage and WriteableBitmap share the same base class, the BitmapSource. Maybe you can change your interfaces to BitmapSource and use the WriteableBitmapEx code. You won't have much luck with BitmapImage. WriteableBitmap is the way to go for dynamic bitmaps.