2015-12-11 47 views
1

我的问题:有没有办法让窗体释放一个打开的图像,而不关闭窗体。如何使窗体发布/关闭/处理图像文件

我的问题:我正在使用C++的窗体窗体。我有一个允许用户编辑.bmp图像的程序。用户从dataGridView中选择想要编辑的图像。这些图像显示在dataGridView的图像列中。当我将图像加载到dataGridView控件中时,表单将打开图像文件并阻止对图像文件进行任何进一步编辑。即使删除了dataGridView控件,也无法编辑图像文件。表单在释放图像文件之前必须完全关闭。

我的代码:

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; 
    }; 
} 

回答

1

Image类创建一个内存映射文件到该位图的像素数据映射到存储器中。这是有效的,它不会占用交换文件中的空间,并且如果RAM页面未被映射,那么它们总是可以从文件重新加载。倾向于位图的问题,它们可能相当大。

但是MMF的确在文件上创建了一个锁,它将不会被释放,直到你用delete操作符处理对象。直到窗户关闭之后,这当然不会发生。

您可以通过对图像进行深层复制来避免这种情况,从而可以快速释放锁定。与位图(图片^)构造函数来完成:

auto img = System::Drawing::Image::FromFile("C:\\Users\\User\\Desktop\\1.bmp")); 
    dgv->Rows>Add(gcnew Bitmap(img)); 
    delete img; 
+0

非常感谢你对这个答案!这很好用!我有这样的感觉是可能的,但不知道如何实现它。 – shirome