GDI +:如何在背景线程上将Graphics对象渲染为位图?

Rob*_*Rob 3 c# multithreading gdi+ image-processing

我想使用GDI +在后台线程上渲染图像.我找到了关于如何使用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(); 
} 
Run Code Online (Sandbox Code Playgroud)

我的问题有两个部分:

  1. 你会如何this.CreateGraphics()在后台线程上完成?可能吗?我的理解是this这个例子中有一个UI对象.因此,如果我在后台线程上进行此处理,我将如何创建图形对象?

  2. 一旦我完成处理,我将如何从我正在使用的Graphics对象中提取位图?我无法找到一个如何做到这一点的好例子.


另外:格式化代码示例时,如何添加换行符?如果有人可以给我发表评论,说明我真的很感激.谢谢!

Guf*_*ffa 12

要绘制位图,您不希望Graphics为UI控件创建对象.您可以Graphics使用以下FromImage方法为位图创建对象:

Graphics g = Graphics.FromImage(theImage);
Run Code Online (Sandbox Code Playgroud)

一个Graphics对象不包含您绘制它的图形,而不是它只是一个工具绘制另一个画布上,这通常是屏幕,但它也可以是一个Bitmap对象.

因此,您不先绘制然后提取位图,首先创建位图,然后创建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);
}
Run Code Online (Sandbox Code Playgroud)