Old Man
Old Man

Reputation: 3445

Saving System.Drawing.Graphics to a png or bmp

I have a Graphics object that I've drawn on the screen and I need to save it to a png or bmp file. Graphics doesn't seem to support that directly, but it must be possible somehow.

What are the steps?

Upvotes: 26

Views: 86040

Answers (5)

Adriano Silva Ribeiro
Adriano Silva Ribeiro

Reputation: 103

Try this, works fine for me...

private void SaveControlImage(Control ctr)
{
    try
    {
        var imagePath = @"C:\Image.png";

        Image bmp = new Bitmap(ctr.Width, ctr.Height);
        var gg = Graphics.FromImage(bmp);
        var rect = ctr.RectangleToScreen(ctr.ClientRectangle);
        gg.CopyFromScreen(rect.Location, Point.Empty, ctr.Size);

        bmp.Save(imagePath);
        Process.Start(imagePath);

    }
    catch (Exception)
    {
        //
    }
}

Upvotes: 6

Curtis Yallop
Curtis Yallop

Reputation: 7329

Here is the code:

Bitmap bitmap = new Bitmap(Convert.ToInt32(1024), Convert.ToInt32(1024), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmap);

// Add drawing commands here
g.Clear(Color.Green);

bitmap.Save(@"C:\Users\johndoe\test.png", ImageFormat.Png);

If your Graphics is on a form, you can use this:

private void DrawImagePointF(PaintEventArgs e)
{
   ... Above code goes here ...

   e.Graphics.DrawImage(bitmap, 0, 0);
}

In addition, to save on a web page, you could use this:

MemoryStream memoryStream = new MemoryStream();
bitmap.Save(memoryStream, ImageFormat.Png);
var pngData = memoryStream.ToArray();

<img src="data:image/png;base64,@(Convert.ToBase64String(pngData))"/>

Graphics objects are a GDI+ drawing surface. They must have an attached device context to draw on ie either a form or an image.

Upvotes: 32

filip-fku
filip-fku

Reputation: 3265

You are likely drawing either to an image or on a control. If on image use

    Image.Save("myfile.png",ImageFormat.Png)

If drawing on control use Control.DrawToBitmap() and then save the returned image as above.

Thanks for the correction - I wasn't aware you can draw directly to the screen.

Upvotes: 1

MusiGenesis
MusiGenesis

Reputation: 75396

Copy it to a Bitmap and then call the bitmap's Save method.

Note that if you're literally drawing to the screen (by grabbing the screen's device context), then the only way to save what you just drew to the screen is to reverse the process by drawing from the screen to a Bitmap. This is possible, but it would obviously be a lot easier to just draw directly to a Bitmap (using the same code you use to draw to the screen).

Upvotes: 9

Cobusve
Cobusve

Reputation: 1570

Graphics graph = CreateGraphics();
Bitmap bmpPicture = new Bitmap("filename.bmp");

graph.DrawImage(bmpPicture, width, height);

Upvotes: 1

Related Questions