0

My program allows the user to draw in a PictureBox.

I'm trying to save the pictureBox1 as a .jpg file but this file is empty.

My save button:

Bitmap bm = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height);
this.pictureBox1.DrawToBitmap(bm, this.pictureBox1.ClientRectangle);
bm.Save(String.Format("{0}.jpg", this.ID));
this.pictureBox1.CreateGraphics().Clear(Color.White);

My draw event:

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    drawNote.isDraw = true;
    drawNote.X = e.X;
    drawNote.Y = e.Y;
}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if(drawNote.isDraw)
    {
        Graphics G = pictureBox1.CreateGraphics();
        G.DrawLine(drawNote.pen, drawNote.X, drawNote.Y, e.X, e.Y);

        drawNote.X = e.X;
        drawNote.Y = e.Y;

    }
}
LopDev
  • 823
  • 10
  • 26
Ohy
  • 3
  • 2

1 Answers1

-1

You should create an empty Bimap set pictureBox1.Image by this bitmap then creat graphics from it, also you must store it in global variable to prevent recreat it.

Like this:

Graphics graphics = null;
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if(drawNote.isDraw)
    {
        if (graphics == null) 
        {
          graphics = pictureBox1.CreateGraphics();
          Bitmap bmp = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height);
          pictureBox1.Image = bmp;
          graphics = Graphics.FromImage(bmp);
          graphics.Clear(Color.White);
        }

        graphics.DrawLine(drawNote.pen, drawNote.X, drawNote.Y, e.X, e.Y);

        graphics.Flush();
        graphics.Save();
        pictureBox1.Refresh();

        drawNote.X = e.X;
        drawNote.Y = e.Y;
    }
}

And you could do this by this simple code:

using (FileStream fileStream = new FileStream(@"C:\test.jpg", FileMode.Create))
{
    pictureBox1.Image.Save(fileStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
Fred
  • 3,365
  • 4
  • 36
  • 57