2017-04-15 35 views
0

我有一個PictureBox稱爲picture 我想這個圖片框的圖像,並將其保存爲的BitmapSource得到C#中的圖片框的BitmapSource

BitmapSource myPic; 
    myPic = picture.Image; 

,但我得到這個錯誤:

嚴重性代碼說明項目文件行抑制狀態 錯誤CS0029無法將類型'System.Drawing.Image'隱式轉換爲'System.Windows.Media.Imaging.BitmapSource'

回答

1

使用這種方法:

public BitmapSource ImageToBitmapSource(System.Drawing.Image image) 
{ 
     var bitmap = new System.Drawing.Bitmap(image); 

     var bitSrc =BitmapToBitmapSource(bitmap); 

     bitmap.Dispose(); 
     bitmap = null; 

     return bitSrc; 
} 

public BitmapSource BitmapToBitmapSource(System.Drawing.Bitmap source) 
{ 
     BitmapSource bitSrc = null; 

     var hBitmap = source.GetHbitmap(); 

     try 
     { 
      bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
       hBitmap, 
       IntPtr.Zero, 
       Int32Rect.Empty, 
       BitmapSizeOptions.FromEmptyOptions()); 
     } 
     catch (Win32Exception) 
     { 
      bitSrc = null; 
     } 

     return bitSrc; 
}