save bitmap ?
-
i draw some rectangles and lines into the the panel object. but how can i save the content in the panel object to a bitmap file ? thanks....::)
If you want to keep what you've drawn to your panel, then I guess you'll have to take a different approach altogether. Am I right that you're calling
myPanel.CreateGraphics()
and then use this Graphics object for painting? In this case, the actions are not recorded anywhere and your panel will be blank after the next paint event it receives (try hiding your panel behind another window and then restoring it...). I think you should use a Bitmap from the start and paint onto this Bitmap using a Graphics object retrieved byGraphics.FromImage()
. In the paint event handler of your panel you paint the bitmap. That way you can also callmyBitmap.Save(...)
to save the contents of the bitmap. Regards, mav -
i draw some rectangles and lines into the the panel object. but how can i save the content in the panel object to a bitmap file ? thanks....::)
What 'mav' said will work, but there's several problems with his approach. If you draw on a
Graphics
object that you obtained fromControl.CreateGraphics
, your elements will be drawn. But if the form needs repainting (perhaps it was covered up by another form), they won't be redrawn. You need to perform your drawing in an override ofOnPaint
(which is passed aPaintEventArgs
that has aGraphics
property that you should use for painting). In order to be able to save that same code to aBitmap
class and then to a file, you'll want to modularize your code like so:private void PaintRectangles(Graphics g)
{
g.DrawRectangle(...); // Draw rectangles or whatever here
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
PaintRectangles(e.Graphics);
}
private void saveBtn_Click(object sender, EventArgs e)
{
using (Bitmap bmp = new Bitmap(panel1.Size.Width,
panel1.Size.Height))
{
using (Graphics g = Graphics.FromImage(bmp))
{
PaintRectangles(g);
}
bmp.Save("filename.png", ImageFormat.Png); // Save as PNG file
}
}Now you've encapsulated your rectangle drawing code into a single method that can draw onto any
Graphics
object, including the form or panel itself (this is only an example, mind you) or aBitmap
. Theusing
statements above make sure that both theBitmap
andGraphics
objects are disposed (very important, otherwise memory may not be freed when necessary and unmanaged objects will linger, causing memory leaks) even if an exception is thrown.Microsoft MVP, Visual C# My Articles