I’d like to use GDI+ to render an image on a background thread. I found this example on how to rotate an image using GDI+, which is the operation I’d like to do.
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();
}
My question has two parts:
-
How would you accomplish
this.CreateGraphics()on a background thread? Is it possible? My understanding is that a UI object isthisin this example. So if I’m doing this processing on a background thread, how would I create a graphics object? -
How would I then extract a bitmap from the Graphics object I’m using once I’m done processing? I haven’t been able to find a good example of how to do that.
Also: when formatting a code sample, how do I add newlines? If someone could leave me a comment explaining that I’d really appreciate it. Thanks!
To draw on a bitmap you don’t want to create a
Graphicsobject for an UI control. You create aGraphicsobject for the bitmap using theFromImagemethod:A
Graphicsobject doesn’t contain the graphics that you draw to it, instead it’s just a tool to draw on another canvas, which is usually the screen, but it can also be aBitmapobject.So, you don’t draw first and then extract the bitmap, you create the bitmap first, then create the
Graphicsobject to draw on it: