且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Windows窗体 - 图片框。如何删除图像

更新时间:2023-12-06 16:28:52

您必须处置图片。忘记这样做使得你的程序可能会在非垃圾收集器运行不够频繁时运行非托管内存。位图对象相当小,你可以分配数千个它们,而不会触发GC,但可能消耗大量的非托管内存的像素数据。在C ++ / CLI中使用 delete 运算符来处理对象,它会调用IDisposable :: Dispose()。

You have to dispose the old image. Forgetting to do so makes it likely your program runs out of unmanaged memory when the garbage collector doesn't run frequently enough. Bitmap objects are quite small, you can allocate thousands of them without ever triggering a GC, but can consume a lot of unmanaged memory for the pixel data. You dispose objects in C++/CLI with the delete operator, it calls IDisposable::Dispose().

请注意,您使用的FileStream也是一次性的对象。这样做需要你在位图使用时保持流打开,然后关闭它。您正确地没有处理流但忘记关闭它。很难得到正确,使用Bitmap构造函数接受文件路径的字符串更容易,因此Bitmap类管理底层流本身。修正:

Do note that the FileStream you use is also a disposable object. Doing it this way requires you to keep the stream opened while the bitmap is in use and close it afterwards. You correctly did not dispose the stream but forgot closing it. Too hard to get right, it is much easier to use the Bitmap constructor that accepts a string for the file path so the Bitmap class manages the underlying stream itself. Fix:

  aux = config->images_path;
  aux += ....;
  System::Drawing::Bitmap^ img = gcnew System::Drawing::Bitmap(aux);
  delete this->pictureBox_image1->Image;
  this->pictureBox_image1->Image = img;