2015-04-07 53 views
1

要轉換的byte []到ImageSource的錯誤轉換字節的ImageSource

這裏是我的轉換代碼,逐字節

public object BufferFromImage(System.Windows.Media.ImageSource imageSource) 
    { 
     if (imageSource != null) 
     { 
      var image = (BitmapSource)imageSource; 
      BitmapEncoder encoder = new PngBitmapEncoder(); 
      encoder.Frames.Add(BitmapFrame.Create(image)); 
      using (var ms = new MemoryStream()) 
      { 
       encoder.Save(ms); 
       return ms.ToArray(); 
      } 
     } 
     else 
     { 
      return DBNull.Value; 
     } 
    } 

代碼[]以ImageSource的

public ImageSource ByteToImage(byte[] imageData) 
    { 
     BitmapImage biImg = new BitmapImage(); 
     MemoryStream ms = new MemoryStream(imageData); 
     biImg.BeginInit(); 
     biImg.StreamSource = ms; 
     biImg.EndInit(); 
     ImageSource imgSrc = biImg as ImageSource; 
     return imgSrc; 
    } 

這給我這個錯誤:

An unhandled exception of type 'System.NotSupportedException' occurred in PresentationCore.dll

Additional information: No imaging component suitable to complete this operation was found.

這是什麼原因造成的?我該如何解決?

+1

[http://stackoverflow.com/問題/ 22065815 /如何對轉換字節數組到ImageSource的換窗戶,8-0商店的應用程序(http://stackoverflow.com/questions/22065815/how-to-convert-byte -array-to-imagesource-for-windows-8-0-store-application) – Eminem

+0

使用此鏈接進行文件上傳http://www.aspsnippets.com/Articles/Save-Files-to-SQL-Server -Database-using-FileUpload-Control.aspx –

+0

http://stackoverflow.com/a/8901493/4513879使用此鏈接也 –

回答

0

看起來你可以將其保存到一個MemoryStream,然後將MemoryStream轉換爲字節array.try這個

public byte[] imageToByteArray(System.Drawing.Image imageIn) 
{ 
MemoryStream ms = new MemoryStream(); 
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif); 
return ms.ToArray 
} 

//第二

public byte[] imgToByteArray(Image img) 
{ 
     using (MemoryStream mStream = new MemoryStream()) 
     { 
      img.Save(mStream, img.RawFormat); 
      return mStream.ToArray(); 
     } 
}