2013-03-11 89 views
1

我正在應用程序中有一個conbobox和一個picturebox。用戶選擇一個路徑,並且conbobox將路徑加載到2000個圖像,並顯示第一個路徑。當用戶更改conbobox的索引時,顯示的圖像會發生變化,但我不知道如何刪除圖片框中的圖像。Windows窗體 - 圖片框。如何刪除圖像

如果我只是覆蓋圖像它沒有做的工作,因爲當我反覆做這個程序崩潰,因爲內存。如何刪除圖片框內的圖片?

編輯: 我做了很少的變化,似乎無法再次重現錯誤..所以也許這是別的。但只是爲了檢查,這是代碼泄漏的內存?

tips:config是一個單獨的元素,包含一些信息,在這種情況下,圖像在哪裏。

private: System::Void comboBox_image1_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) { 
     System::String^ aux; 
     DIC_config* config=DIC_config::Instance(); 
     if(config->images_path!=NULL){ 
      aux=gcnew System::String(config->images_path); 
      aux=aux+"\\CAM_0\\Snap_0_0"+(this->comboBox_image1->SelectedIndex+1)+".bmp"; 
      System::IO::FileStream^ image_file=gcnew System::IO::FileStream(aux,System::IO::FileMode::Open,System::IO::FileAccess::Read); 
      System::Drawing::Bitmap^ img = gcnew System::Drawing::Bitmap(image_file); 
      this->pictureBox_image1->Image=img; 
      //img->~Bitmap(); this doesnt work, deletes the image of picturebox and makes the program chrash 
     } 

    } 
+1

你確定你有C++項目? – VladL 2013-03-11 09:44:09

+0

我們已經在您的Sample中看到了C#代碼...確認編程語言.... – Pandian 2013-03-11 09:50:17

+0

@VladL對不起,剛剛從別處複製代碼是因爲我在編輯我的項目,但它並不完全正確。我有一個C++項目,不用擔心。這個想法仍然是一樣的。 – 2013-03-11 10:01:24

回答

3

你必須處置圖像。如果忘記這麼做,那麼當垃圾收集器運行不夠頻繁時,您的程序可能會耗盡非託管內存。位圖對象非常小,您可以在不觸發GC的情況下分配數千個對象,但可以爲像素數據消耗大量非託管內存。您使用刪除運算符在C++/CLI中處理對象,它調用IDisposable :: Dispose()。

請注意,您使用的FileStream也是一次性對象。這樣做需要您在位圖正在使用時保持打開的流,然後關閉它。你正確地沒有處理流,但忘記關閉它。太難以正確使用接受字符串作爲文件路徑的Bitmap構造函數,因此Bitmap類自己管理底層流更容易。修復:

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

非常感謝,我希望我能接受這兩個答案。 – 2013-03-11 11:27:03

+0

按照您接受的答案中的建議,不要**調用image_file->關閉()。流**必須**保持打開,而位圖可以被繪製。您確實非常想要支持Bitmap(String)構造函數。 – 2013-03-11 11:32:46

2

這不起作用,因爲您試圖調用類的析構函數,而不是實例。此外,由於System::Drawing::Bitmap在垃圾收集器的控制下,所以不需要調用它,因此如果不再引用終結器(!Bitmap()),它將自動調用。

如果你想關閉它在圖片框,你可以做的是

delete this->pictureBox_image1->Image; 
image_file->Close(); //after closing/deleting the open bitmap 

BTW。你的代碼是不是純粹的C++,但C++/CLI,所以,我已經添加了標籤

+0

我不能這樣做。this-> pictureBox_image1-> Image = null;它說null沒有被定義。相反,如果我寫NULL它說,不能從int轉換爲圖像... – 2013-03-11 11:14:07

+0

既不close()是System :: Drawing :: Bitmap的方法... – 2013-03-11 11:17:40

+0

@AnderBiguri似乎你是正確的,刪除​​this-> pictureBox_image1 - >圖片應該做的工作 – VladL 2013-03-11 11:18:13

0

首先設置一個空指針圖像屬性並刷新圖片框下面給出,

pictureBox_image1->Image = nullptr; 
pictureBox_image1->Refresh();