2012-08-29 133 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; 
} 
相关问题