3

I need to have image file path from the user and store the image in my sql server database.

I get the file from the user and convert to byte[] using the method

public static byte[] ImageToByteArray( BitmapSource bitmapSource )
    {
        byte[] imgAsByteArray = null;

        if( bitmapSource != null )
        {
            imgAsByteArray = ( new WriteableBitmap( ( BitmapSource )bitmapSource ) ).Pixels.SelectMany( p => new byte[] 
            { 

                ( byte )  p        , 
                ( byte )( p >> 8  ), 
                ( byte )( p >> 16 ), 
                ( byte )( p >> 24 ) 

            } ).ToArray(); 
        }

        return imgAsByteArray;
    }

but now i can't convert it back to BitmapSource. The code that i wrote to convert it back throw an exception

The code:

public static BitmapSourcebyteArrayToImage( byte[] imageBytes )
    {
        BitmapImage bitmapImage = null;
        using( MemoryStream ms = new MemoryStream( imageBytes, 0, imageBytes.Length ) )
        {
            bitmapImage = new BitmapImage();
            bitmapImage.SetSource( ms );    
        }

        return (BitmapSource)bitmapImage;
    }

I get the exception on the line bitmapImage.SetSource( ms );
The exception information is 'catastropic fail'

Yanshof
  • 9,659
  • 21
  • 95
  • 195

1 Answers1

2

Maybe SetSource does not read the MemoryStream but links to it and when you later use the BitmapSource silverlight wants to use the MemoryStream to get the image but because of your using it is already disposed and no longer valid.

ZoolWay
  • 5,411
  • 6
  • 42
  • 76
  • the data look Ok - i dont see any place there can be data dispose – Yanshof May 05 '11 at 07:42
  • 1
    When exiting you using-area it implicitly calls `ms.Dispose()`. That is what `using` is for. But as your exception occurs within that, this is not the answer I guess. – ZoolWay May 05 '11 at 07:44