c# - GDI+:如何在后台线程上将 Graphics 对象渲染为位图?

标签 c# multithreading image-processing gdi+

我想使用 GDI+ 在后台线程上渲染图像。我找到了 this example关于如何使用 GDI+ 旋转图像,这是我想做的操作。

private void RotationMenu_Click(object sender, System.EventArgs e)
{
    Graphics g = this.CreateGraphics();
    g.Clear(this.BackColor);
    Bitmap curBitmap = new Bitmap(@"roses.jpg"); 
    g.DrawImage(curBitmap, 0, 0, 200, 200);  

    // Create a Matrix object, call its Rotate method,
    // and set it as Graphics.Transform
    Matrix X = new Matrix();
    X.Rotate(30);
    g.Transform = X;  

    // Draw image
    g.DrawImage(curBitmap, 
    new Rectangle(205, 0, 200, 200), 
        0, 0, curBitmap.Width, 
        curBitmap.Height, 
        GraphicsUnit.Pixel);  

    // Dispose of objects
    curBitmap.Dispose();
    g.Dispose(); 
} 

我的问题分为两部分:

  1. 您将如何在后台线程上完成 this.CreateGraphics()?是否可以?我的理解是,在这个例子中,UI 对象是 this。因此,如果我在后台线程上执行此处理,我将如何创建图形对象?

  2. 处理完成后,我该如何从正在使用的 Graphics 对象中提取位图?我还没有找到一个很好的例子来说明如何做到这一点。


另外:格式化代码示例时,如何添加换行符?如果有人可以给我留言解释我将非常感激。谢谢!

最佳答案

要在位图上绘图,您不想为 UI 控件创建 Graphics 对象。您使用 FromImage 方法为位图创建一个 Graphics 对象:

Graphics g = Graphics.FromImage(theImage);

Graphics 对象不包含您向其绘制的图形,它只是在另一个 Canvas (通常是屏幕)上绘制的工具,但也可以是 位图对象。

因此,您不是先绘制再提取位图,而是先创建位图,然后创建 Graphics 对象以在其上绘制:

Bitmap destination = new Bitmap(200, 200);
using (Graphics g = Graphics.FromImage(destination)) {
   Matrix rotation = new Matrix();
   rotation.Rotate(30);
   g.Transform = rotation;
   g.DrawImage(source, 0, 0, 200, 200);
}

关于c# - GDI+:如何在后台线程上将 Graphics 对象渲染为位图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/917294/

相关文章:

java - 捕获 A4 大小的文档。 OpenCV 可以在 Android 中执行此操作吗?

c# - 获取 VPN IP 地址

c# - Linq 查询数组中的每个元素

c - OpenCV中两点之间的距离

java - 如何管理超过 32k 的线程

java - 查询 Google App Engine 数据存储区时出现并发问题

python - 使用Python从图像背景中提取相同颜色的前景

c# - 需要帮助设计进程间通信层

c# - VisualStudio 解决方案中的条件项目路径变量

java - 连接未被释放到多线程程序中的池