如何将ImageSource转换为byte []并返回ImageSource?

时间:2011-05-05 07:34:48

标签: silverlight

我需要有来自用户的图像文件路径并将图像存储在我的sql server数据库中。

我从用户那里获取文件并使用方法

转换为byte []
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;
    }

但现在我无法将其转换回BitmapSource。 我编写的用于转换它的代码抛出异常

代码:

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;
    }

我在行bitmapImage.SetSource(ms)上得到了异常;
异常信息是“灾难性失败”

1 个答案:

答案 0 :(得分:2)

也许SetSource没有读取MemoryStream但链接到它,当你以后使用BitmapSource时,silverlight希望使用MemoryStream来获取图像,但由于你的使用它已经被处理掉了,不再有效。 / p>