C++ 如何使windows窗体释放/关闭/处置图像文件
我的问题:有没有办法让windows窗体在不关闭窗体的情况下释放打开的映像 我的问题是:我正在用C++编写Windows窗体。我有一个程序,允许用户编辑.bmp图像。用户从dataGridView中选择要编辑的图像。图像显示在dataGridView的图像列中。当我将图像加载到dataGridView控件中时,表单会打开图像文件,并阻止对图像文件进行任何进一步的编辑。即使删除了dataGridView控件,也无法编辑图像文件。表单必须在释放图像文件之前完全关闭 我的代码:C++ 如何使windows窗体释放/关闭/处置图像文件,c++,image,winforms,datagridview,C++,Image,Winforms,Datagridview,我的问题:有没有办法让windows窗体在不关闭窗体的情况下释放打开的映像 我的问题是:我正在用C++编写Windows窗体。我有一个程序,允许用户编辑.bmp图像。用户从dataGridView中选择要编辑的图像。图像显示在dataGridView的图像列中。当我将图像加载到dataGridView控件中时,表单会打开图像文件,并阻止对图像文件进行任何进一步的编辑。即使删除了dataGridView控件,也无法编辑图像文件。表单必须在释放图像文件之前完全关闭 我的代码: namespace E
namespace EditImageTest {
public ref class Form1 : public System::Windows::Forms::Form {
public: Form1(void) {
// create an image column & dataGridView.
System::Windows::Forms::DataGridViewImageColumn^ c = gcnew System::Windows::Forms::DataGridViewImageColumn();
c->ImageLayout = System::Windows::Forms::DataGridViewImageCellLayout::Zoom;
System::Windows::Forms::DataGridView^ dgv = gcnew System::Windows::Forms::DataGridView();
// add column to dataGridView.
dgv->Columns->Add(c);
// add dataGridView to form.
this->Controls->Add(dgv);
// add .bmp image on desktop to dataGridView.
dgv->Rows>Add(System::Drawing::Image::FromFile("C:\\Users\\User\\Desktop\\1.bmp"));
// the form has now opened the .bmp image file preventing any edits on this file.
// you can not even manualy delete this file now.
// attempt to open the .bmp image for editing.
FILE* f;
fopen_s(&f,"C:\\Users\\User\\Desktop\\1.bmp","w");
if(f) {
// write garbage in the .bmp image.
fwrite("SOME TEXT",sizeof(unsigned char),9,f);
// close the .bmp image.
fclose(f);
}
}
protected: ~Form1() { if (components) { delete components; } }
private: System::ComponentModel::Container ^components;
};
}
Image类创建一个内存映射文件,将位图的像素数据映射到内存中。这是有效的,它不会占用交换文件中的空间,如果RAM页面未映射,那么它们总是可以从文件中重新加载。对于位图来说很重要,它们可能非常大 但是MMF确实在文件上创建了一个锁,在您使用delete操作符处理对象之前,它不会被释放。当然,在窗户关上之前是不会发生的 您可以通过制作图像的深度副本来避免这种情况,从而快速释放锁。使用位图(图像^)构造函数执行此操作:
auto img = System::Drawing::Image::FromFile("C:\\Users\\User\\Desktop\\1.bmp"));
dgv->Rows>Add(gcnew Bitmap(img));
delete img;
非常感谢你的回答!这太棒了!我有一种感觉,像这样的事情是可能的,但不太知道如何实现它。