如何从设备上下文创建位图

本文关键字:上下文 创建 位图 | 更新日期: 2023-09-27 18:30:54

我一直在绘制设备上下文,现在我希望能够将设备上下文的内容保存到图像中。如果直接从位图保存不是最佳方法,那么如何从设备上下文获取到位图?我正在尝试在 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();
                   }

如何从设备上下文创建位图

// 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+(主要是软件呈现的),因此性能不是太大问题,因为您要呈现到静态文件。

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