Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to erase content on a Bitmap

I have C# winForm application which holds a pictureBox control. This control has a Paint event. Every time paint event is fired , a Bitmap is dynamically created and I perform some drawing on it. And when user clicks "save" button , edited image is saved as jpg file.

It's OK until now. When I load a new image in pictureBox control remains of previous edits are still alive.

How can I erase the bitmap and start fresh each time I load a new image:

private void pb_Resim_Paint(object sender, PaintEventArgs e)
{
  List<eVucutParcalari> list = new List<eVucutParcalari>(pointList.Keys);
  // Loop through list
  foreach (eVucutParcalari k in list)
  {
    Dictionary<Point, Color> dicItem = pointList[k];
    foreach (KeyValuePair<Point, Color> pair in dicItem)
    {
      Point p = pair.Key;
      Color c = pair.Value;
      SolidBrush brush = new SolidBrush(c);

      if (pb_Resim.Image == null)
        return;
      Bitmap bmp = new Bitmap(pb_Resim.Image);
      Graphics gr = Graphics.FromImage(bmp);
      gr.FillRectangle(brush, p.X, p.Y, 5, 5);
      pb_Resim.Image = bmp;
    }
  }
}

1 Answers

Why not create a brand new bitmap when you load a new file, and replace the bitmap currently assigned to pb_Resim.Image on load? This would allow the old bitmap to be collected by the GC without requiring you to expend any effort "clearing" the previous bitmap, and ensure that you have a brand new, fresh bitmap without any residual junk of any kind for the newly loaded file.

like image 85
jrista Avatar answered Nov 26 '25 13:11

jrista



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!