20

How can I convert graphics object to bitmap object using C#?

Zach Johnson
  • 22,702
  • 6
  • 67
  • 85
Binu
  • 1,295
  • 5
  • 13
  • 22

3 Answers3

23
Bitmap myBitmap = new Bitmap(width, height, myGraphics);

Alternatively:

Graphics myGraphics = Graphics.FromImage(myBitmap);
// some code with draw on myGraphics
myGraphics.Dispose();
AndreyAkinshin
  • 17,723
  • 28
  • 93
  • 152
  • 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
  • 42,334
  • 17
  • 98
  • 130
Andrew Keith
  • 7,382
  • 1
  • 23
  • 39
  • 11
    The 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
1

This looks like what you might want: DaniWeb, yes annoyingware but it does provide a working solution

warren
  • 30,458
  • 19
  • 84
  • 116
monksy
  • 13,936
  • 16
  • 71
  • 122