【问题标题】:Show a System.Windows.Media.Imaging.BitmapSource in a PictureBox in WindowsForm in C#在 C# 中的 WindowsForm 中的 PictureBox 中显示 System.Windows.Media.Imaging.BitmapSource
【发布时间】:2012-08-29 12:46:10
【问题描述】:

我想在图片框中绘制一个 System.Windows.Media.Imaging.BitmapSource。 在 WPF 应用程序中,我这样做:

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

但现在我有一个表格。我在我的表单中导入 PresentationCore.dll 以获得 BitmapSource; 但是现在我如何在这样的 PictureBox 上绘制或显示它? :

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

请帮助我。 谢谢。

【问题讨论】:

    标签: c# .net wpf winforms picturebox


    【解决方案1】:

    为什么你想要/需要使用 wpf 特定的东西?

    看看这个sn-p 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");
    

    【讨论】:

    • 非常感谢。你的解决方案解决了我的问题。谢谢
    【解决方案2】:

    你还好吗?

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

    【讨论】:

    【解决方案3】:

    这种方法性能更好(快两倍)并且需要更少的内存,因为它不会将数据复制到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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      • 2016-07-08
      • 2012-09-21
      • 2017-01-01
      • 1970-01-01
      相关资源
      最近更新 更多