2016-06-09 55 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