2015-04-07 41 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(); 
     } 
}