在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+. 

这是一个常见问题。

文件说:

不允许将图像保存到它构造的同一文件中并引发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文件通常可以获得更好的质量。 使用此重载为此..

另请注意,因为我们需要处理您需要的图像,以确保它不会在任何地方使用,例如在PictureBox.Image ! 如果是,则在处理之前将其设置为nullpictureBox1.Image = null;

有关删除旧文件的解决方案,请参阅此处