Converting byte[] to .Net image

O

Oriane

Hello there,

I try to handle bitmap images stored in an Image column in Sql Server. The
following code is ok when the image is of type Bitmap (*.bmp):

private ImageSource ConvertByteArrayToImageSource(byte[] bdIconeArray) {
ImageSource imgSource = null;
MemoryStream strm = new MemoryStream();
BitmapImage bitmap = new BitmapImage();

// Well-known work-around to make Northwind images work
int offset = 78;
strm.Write( bdIconeArray, offset, bdIconeArray.Length - offset );

// Read the image into the bitmap object
bitmap.BeginInit();
bitmap.StreamSource = strm;
bitmap.EndInit();

imgSource = bitmap;
return imgSource;
}

However, it doesn't work with png, jpg or Tiff image stored in the database.
Must the Offset be different ?

Oriane
 
K

Kevin Spencer

You need to use a Decoder to translate the format. There is a
JpegBitmapDecoder class, a TiffBitmapDecoder class, and a PngBitmapDecoder
class. Here's a link to the JpegBitmapDecoder class, from which you can get
the documentation and sample code, as well as navigate to the similar
documentation for the other decoder classes:

http://msdn2.microsoft.com/en-us/library/system.windows.media.imaging.jpegbitmapdecoder.aspx

--
HTH,

Kevin Spencer
Chicken Salad Surgeon
Microsoft MVP
 
O

Oriane

Hi Kevin,

Kevin Spencer said:
You need to use a Decoder to translate the format. There is a
JpegBitmapDecoder class, a TiffBitmapDecoder class, and a PngBitmapDecoder
class. Here's a link to the JpegBitmapDecoder class, from which you can
get the documentation and sample code, as well as navigate to the similar
documentation for the other decoder classes:

http://msdn2.microsoft.com/en-us/library/system.windows.media.imaging.jpegbitmapdecoder.aspx
I've tried this code:
_____________________________________________________________________________
Byte [] dbIconeArray = ... // Get from Sql Server
MemoryStream strm = new MemoryStream();

// Well-known work-around to make Northwind images work
int offset = 0;
strm.Write( bdIconeArray, offset, bdIconeArray.Length - offset );
BmpBitmapDecoder decoder = new BmpBitmapDecoder(strm,
BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = decoder.Frames[0];
imgSource = bitmapSource;
______________________________________________________________________________________

and I get an exception.

Now if I set (like before) thge variable offset to 78, it works !!!

The same code with PngBitmapDecoder fails with offset = 0 or offset=78.

Thanks a lot !
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top