简体   繁体   中英

Set C# Picturebox to Bitmap

I have a very basic problem. I have a variable of type: Bitmap. This variable updates with every frame received from the webcam. This variable is declared as follows:

Bitmap img=eventArgs.Frame;

I have verified that the above line is working properly. All I need to know now is how to set my PictureBox on my form to this Bitmap image. I have tried the following:

pbImg.Image=img;

This doesn't work. Any help would be greatly appreciated.

Bitmaps generated by a camera normally only have a very short life-time. They are only valid while the event handler runs, the camera capture driver replaces the bitmap with a new frame. Pretty essential to avoid excessive memory usage.

You must therefore make a deep copy of the image so that it can survive in the PictureBox and still get painted after the event call completed. Like this:

  Bitmap img = new Bitmap(eventArgs.Frame);
  if (pbImg.Image != null) pbImg.Image.Dispose();
  pbImg.Image = img;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM