2016-06-09 59 views
0

我正在做一個應用程序, 我添加一個圖片框添加圖片到一些產品,我有一個問題,我想編輯已添加到一個產品的圖片,我該怎麼做? 這是我的實際代碼。在C#中覆蓋圖像的圖片框#

private void pbImagenEquipo_DoubleClick(object sender, EventArgs e) 
{ 
    ofdImagenes.Filter = "Imagenes JPG (*.jpg)|*.jpg; *.jpeg;|Imagenes PNG (*.png)|*.png"; 
    DialogResult resp = ofdImagenes.ShowDialog(); 
    if (resp == DialogResult.OK) 
    { 
     Bitmap b = new Bitmap(ofdImagenes.FileName); 
     string [] archivo = ofdImagenes.FileName.Split('.'); 
     nombre = "Equipo_" + lbID+ "." + archivo[archivo.Length-1]; 

     b.Save(Path.Combine(Application.StartupPath, "Imagenes", nombre)); 

     pbImagenEquipo.Image = b; 

    } 
} 

但是,當我試圖取代我得到這個錯誤形象:

An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll 

Additional information: Error generoc in e GDI+. 
+1

通過「我想編輯的圖像已經添加到一個產品,」你的意思是讓用戶選擇一個新的文件,並覆蓋原文件,並更新圖像在用戶界面?這個錯誤會引發什麼?新的位圖? b.Save? Image = b? – Tom

+0

@TomA,是的,那是對的。 「你的意思是讓用戶選擇一個新文件並覆蓋原始文件並更新UI中的圖像?」我有這條線上的錯誤:b.Save(Path.Combine(Application.StartupPath,「Imagenes」,nombre)); – Fernando

回答

1

這是一個常見的問題。

documentation說:

Saving the image to the same file it was constructed from is not allowed and throws an exception.

有兩個選項。一種是在寫入文件之前刪除文件。

另一種是使用Stream來寫它。我更喜歡後者..:

string fn = "d:\\xyz.jpg"; 

// read image file 
Image oldImg = Image.FromFile(fn); 

// do something (optional ;-) 
((Bitmap)oldImg).SetResolution(123, 234); 

// save to a memorystream 
MemoryStream ms = new MemoryStream(); 
oldImg.Save(ms, ImageFormat.Jpeg); 

// dispose old image 
oldImg.Dispose(); 

// save new image to same filename 
Image newImage = Image.FromStream(ms); 
newImage.Save(fn); 

注意節電jpeg文件通常達到更好的質量,如果你採取的編碼選項控制。使用this overload這個..

還要注意,由於我們需要配置,你需要確保它不是在PictureBox.Image任何地方使用,如圖像的!如果是,則在處置前將其設置爲nullpictureBox1.Image = null;

有關解決方案刪除舊文件中看到here