Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert ImageSource to byte[] and back to ImageSource?

Tags:

silverlight

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'

like image 268
Yanshof Avatar asked Dec 01 '25 03:12

Yanshof


1 Answers

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.

like image 166
ZoolWay Avatar answered Dec 06 '25 08:12

ZoolWay