20

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

Zach Johnson
  • 23,678
  • 6
  • 69
  • 86
Binu
  • 1,365
  • 5
  • 14
  • 23

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
  • 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
  • 12
    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
  • 32,620
  • 21
  • 85
  • 124
monksy
  • 14,156
  • 17
  • 75
  • 124