开发者

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

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 &g开发者_如何学编程t;> 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'


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜