2011-05-05 42 views
3

我需要从用户的图像文件路径,并将图像存储在我的sql服务器数据库。如何将ImageSource转换为byte []并返回ImageSource?

我从用户的文件,并转换为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)除外;
异常信息是“catastropic失败”

+0

哪一行导致异常? – ZoolWay 2011-05-05 07:38:35

+0

line bitmapImage.SetSource(ms); – Yanshof 2011-05-05 07:41:44

+0

图像格式为JPG – Yanshof 2011-05-05 08:04:42

回答

2

也许SetSource不读的MemoryStream,但它的链接,并在以后使用的BitmapSource的Silverlight希望使用的MemoryStream来获取图像,而是因为你使用的是已经处置和不再有效。

+0

数据看起来好 - 我没有看到任何可以有数据配置的地方 – Yanshof 2011-05-05 07:42:31

+1

当退出使用区时,它会隐式调用ms.Dispose()。这就是“使用”的意思。但是,因为你的例外发生在那里,这不是我想的答案。 – ZoolWay 2011-05-05 07:44:41