Alejandro Piad
Alejandro Piad

Reputation: 1877

Saving a Graphics content to a file

I have some code where I draw a function graph into a PictureBox graphics. The code is implemented in the Paint event. At some point I want to save a bitmap of the content of the graphics in a file.

I already read the answers to this question, and didn't found what I was looking for.

What I need is both to draw in the PictureBox (or any other control that you suggest) so that I don't loose the drawing when the control is hidden or something (so I think I cannot CreateGraphics()) and be able to save that drawing in a button's click event.

I'm willing to put the drawing logic out of the Paint event if necesary.

Thanks in advance.

Upvotes: 1

Views: 1886

Answers (1)

General Grey
General Grey

Reputation: 3688

I went ahead and answered the question based on my assumption,

I created a new Winforms application

I added a panel and a button I created a Bitmap named buffer, and in the Form1 constructor, initialized it to the size of the panel. Instead of drawing directly to the panel, I draw to the Bitmap, then set the panels background image buffer; This will add persistance to your graphics. If you truly wish to write to a file, I can show you that. Just ask.

To write to file you will need this namespace reference :

using System.IO;

I added the ImageToDisc function you were asking for.

Here is the Code :

Bitmap buffer;
public Form1()
{
    InitializeComponent();
    panel1.BorderStyle = BorderStyle.FixedSingle;
    buffer = new Bitmap(panel1.Width,panel1.Height);
}

private void button1_Click(object sender, EventArgs e)
{
    using (Graphics g = Graphics.FromImage(buffer))
    {
        g.DrawRectangle(Pens.Red, 100, 100,100,100);
    }

    panel1.BackgroundImage = buffer;
    //writes the buffer Bitmap to a binary file, only neccessary if you want to save to disc
    ImageToDisc();
    //just to prove that it did write it to file and can be loaded I set the mainforms background image to the file
    this.BackgroundImage=FileToImage();
}

//Converts the image to a byte[] and writes it to disc
public void ImageToDisc()
{
    ImageConverter converter = new ImageConverter();
    File.WriteAllBytes(@"c:\test.dat", (byte[])converter.ConvertTo(buffer, typeof(byte[])));
}

//Converts the image from disc to an image
public Bitmap FileToImage()
{
    ImageConverter converter = new ImageConverter();
    return (Bitmap)converter.ConvertFrom(File.ReadAllBytes(@"c:\test.dat"));
}

Upvotes: 1

Related Questions