0

I am showing the images that I capture from two cameras in a picturebox (the same for both). Each camera image is shown in a different ROI of the picturebox.

My problem is that the memory used by the application is increasing continuously, most probably I am missing freeing some resources, but I cannot find what I am missing.

This is the code:

// bitmap: input new image
// srcRoi: a rectangle with the ROI for the input image
// dstRoi: a rectangle with the ROI for the pictureBox
// reset: true for the first camera, false for the second one.
if (reset)
{
    pictureBoxPreview1.Image.Dispose();
}
if (pictureBoxPreview1.Image == null || reset)
{
    pictureBoxPreview1.Image = new Bitmap(pictureBoxPreview1.Width,
        pictureBoxPreview1.Height);
}
using (Graphics g = Graphics.FromImage(pictureBoxPreview1.Image))
{
    using (var img = Image.FromHbitmap(bitmap.GetHbitmap()))
    {
        g.DrawImage(img, dstRoi, srcRoi, GraphicsUnit.Pixel);
    }
}
if (reset) {
    pictureBoxPreview1.Invalidate();
}

The problem is not happening if pictureBoxPreview1.Image.Dispose() is call for both cameras, but then only the image of one camera is shown each time.

I don't understand why if I am only creating a new image and disposing it for half of the images the problem is solved when the same thing is done for all the images.

Braiam
  • 1
  • 11
  • 47
  • 78
mompes
  • 53
  • 5
  • Are you actually disposing of `bitmap`? The snippet you've posted isn't really easy to follow, and is missing quite a few parts. Why do you think the problem is in this code? Why do you think that always recreating the bitmap (and disposing the old one) gets rid of the problem? It might only be making it less apparent (for whatever reason). Don't use `bitmap.GetHBitmap` - you need to dispose of it, and it's unecessary - just draw the `bitmap` directly (`Bitmap` inherits from `Image`, so you can just `DrawImage(bitmap, ...)`). – Luaan May 19 '15 at 12:42
  • @Luaan you were right, the problem was the bitmap.GetHBitmap. I tried to reduce the code to the minimum so it was easier to understand, it looks like it wasn't... – mompes May 19 '15 at 13:21

1 Answers1

1

You can follow the answer from the following link WPF CreateBitmapSourceFromHBitmap() memory leak

In brief bitmap.GetHbitmap() is leaking and must be disposed

BTW in case of your bitmap being System.Drawing.Bitmap you can just write

g.DrawImage(bitmap, dstRoi, srcRoi, GraphicsUnit.Pixel);

since Bitmap is Image

BTW you can cache your image by picture box size and reuse it until resized.

Community
  • 1
  • 1
Igor Popov
  • 2,084
  • 16
  • 18
  • Thanks a lot, it works now like a charm. The bitmap.GetHbitmap() was leaking and since the bitmap is a System.Drawing.Bitmap I just wrote your suggestion. – mompes May 19 '15 at 13:19