2012-08-29 77 views
3

我想繪製一個圖片框中的System.Windows.Media.Imaging.BitmapSource。 在WPF應用程序,我這個做:在WindowsForm中的PictureBox中顯示System.Windows.Media.Imaging.BitmapSource C#

image1.Source =BitmapSource.Create(....................); 

,但現在我有一個表格。我在表單中導入PresentationCore.dll以使用BitmapSource; 但現在我如何繪製或顯示它在這樣的PictureBox? :

pictureBox1.Image=BitmapSource.Create(.....................); 

請幫幫我。 謝謝。

回答

2

你爲什麼要/需要使用特定於wpf的東西?

看看這個片斷 How to convert BitmapSource to Bitmap

Bitmap BitmapFromSource(BitmapSource bitmapsource) 
{ 
    Bitmap bitmap; 
    using (MemoryStream outStream = new MemoryStream()) 
    { 
     BitmapEncoder enc = new BmpBitmapEncoder(); 
     enc.Frames.Add(BitmapFrame.Create(bitmapsource)); 
     enc.Save(outStream); 
     bitmap = new Bitmap(outStream); 
    } 
    return bitmap; 
} 

用法:

pictureBox1.Image = BitmapFromSource(yourBitmapSource); 

如果你想打開圖像文件...:

pictureBox1.Image = System.Drawing.Image.FromFile("C:\\image.jpg"); 
+0

非常感謝你。我的問題已解決您的解決方案。謝謝 –

0

這對你OK ?

ImageSource imgSourceFromBitmap = Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); 
+0

此代碼泄漏HBITMAP句柄,您必須調用'DeleteObject()'。 http://msdn.microsoft.com/library/1dz311e4.aspx –

0

此方法具有更好的性能(快兩倍),並且需要較低的內存,因爲它不會將數據複製到MemoryStream

Bitmap GetBitmapFromSource(BitmapSource source) //, bool alphaTransparency 
{ 
    //convert image pixel format: 
    var bs32 = new FormatConvertedBitmap(); //inherits from BitmapSource 
    bs32.BeginInit(); 
    bs32.Source = source; 
    bs32.DestinationFormat = System.Windows.Media.PixelFormats.Bgra32; 
    bs32.EndInit(); 
    //source = bs32; 

    //now convert it to Bitmap: 
    Bitmap bmp = new Bitmap(bs32.PixelWidth, bs32.PixelHeight, PixelFormat.Format32bppArgb); 
    BitmapData data = bmp.LockBits(new Rectangle(Point.Empty, bmp.Size), ImageLockMode.WriteOnly, bmp.PixelFormat); 
    bs32.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride); 
    bmp.UnlockBits(data); 
    return bmp; 
} 
相關問題