【问题标题】:How to create a bitmap from a Device Context?如何从设备上下文创建位图?
【发布时间】:2013-09-15 18:35:45
【问题描述】:

我一直在绘制设备上下文,现在我希望能够将设备上下文的内容保存到图像中。如果直接从位图保存不是最好的方法,那么我怎样才能从设备上下文中获取位图?我正在尝试在 C# 中执行此操作。

编辑:感谢 SeriesOne,我能够修改他的代码以将 DC 保存到 BMP 中。以下是我的更改方式:

  Rectangle bmpRect = new Rectangle(0, 0, 640, 480);
                   // Create a bitmap
                   using (Bitmap bmp = new Bitmap(bmpRect.Width, bmpRect.Height))
                   {
                       Graphics gfx = Graphics.FromHdc(hdcScreen);
                       bmp.Save("C:\\MyBitmap.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
                       gfx.Dispose();
                   }

【问题讨论】:

  • 显示您目前拥有的代码,并更清楚地说明您想进一步使用它做什么。

标签: c# bitmap pinvoke gdi


【解决方案1】:
// Set the size/location of your bitmap rectangle.    
Rectangle bmpRect = new Rectangle(0, 0, 640, 480);
    // Create a bitmap
    using (Bitmap bmp = new Bitmap(bmpRect.Width, bmpRect.Height))
    {
        // Create a graphics context to draw to your bitmap.
        using (Graphics gfx = Graphics.FromImage(bmp))
        {
            //Do some cool drawing stuff here
            gfx.DrawEllipse(Pens.Red, bmpRect);
        }

        //and save it!
        bmp.Save(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\MyBitmap.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
    }

如果您想将位图另存为文件,这很有效。这使用 GDI+(主要是软件渲染),因此性能不是什么大问题,因为您正在渲染到静态文件。

您还可以在渲染控件时使用它来创建屏幕外图形缓冲区。在这种情况下,您只需删除保存语句,并将位图内容写入控件设备上下文。

【讨论】:

  • 我最终使用并修改了它。
  • @user1632018,很酷,很高兴我能帮上忙!我在您的示例中看到,您已决定删除 using 语句并继续创建 Graphics 实例,然后在完成后将其处理 (.Dispose())。仅供参考, using 语句会自动为您执行此操作。事实上,除非你“使用”的对象实现了 IDisposable,否则你甚至不能使用 using 语句。
猜你喜欢
  • 2012-07-27
  • 2016-01-15
  • 2016-01-08
  • 2023-03-23
  • 2014-02-28
  • 1970-01-01
  • 2011-09-18
  • 2013-05-04
  • 2013-08-02
相关资源
最近更新 更多