How can I convert graphics object to bitmap object using C#?
Asked
Active
Viewed 8.0k times
20
-
What do you want to do with it? Draw on `Graphics` object and save as image file? – TheVillageIdiot Oct 08 '09 at 05:17
3 Answers
23
Bitmap myBitmap = new Bitmap(width, height, myGraphics);
Alternatively:
Graphics myGraphics = Graphics.FromImage(myBitmap);
// some code with draw on myGraphics
myGraphics.Dispose();

AndreyAkinshin
- 18,603
- 29
- 96
- 155
-
5`new Bitmap(.., my Graphics)` does **not** copy the pixels of the graphics into the bitmap, nor otherwise give access to the contents of `myGraphics`. The second solution is a solution to a different problem (somewhat the opposite of what was asked): how to draw into a bitmap using `Graphics` methods. – ToolmakerSteve Sep 22 '17 at 19:25
-
Once I created a [`ToBitmap`](https://docs.kgysoft.net/drawing/?topic=html/M_KGySoft_Drawing_GraphicsExtensions_ToBitmap.htm) extension exactly for this purpose. [NuGet](https://www.nuget.org/packages/KGySoft.Drawing/) and [source](https://github.com/koszeggy/KGySoft.Drawing) are both available. Remark: the `ToBitmap` extension works on Windows only. – György Kőszeg Jul 03 '21 at 10:16
10
Do you mean System.Drawing.Graphics
? The Graphics class is a surface to an image and is already a bitmap.
What are you trying to do with it ?
using(Graphics g = Graphics.FromImage(bitmap))
{
//draw here
}
or
Bitmap bmp = new Bitmap(100,100,graphics);

fubo
- 44,811
- 17
- 103
- 137

Andrew Keith
- 7,515
- 1
- 25
- 41
-
12The docs just say *The Graphics object that specifies the resolution for the new Bitmap.*; doesn't quite sound like anything from the `Graphics` object is copied. – O. R. Mapper Apr 10 '13 at 13:09