在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
! 如果是,则在处理之前将其设置为null
: pictureBox1.Image = null;
!
有关删除旧文件的解决方案,请参阅此处
- 如何将凭据传递给计算机,以便我可以使用Microsoft.Win32.RegistryKey.OpenRemoteBaseKey()?
- 如何使用客户端证书在Web API中进行身份validation和授权
- 如何声明具有匿名类型的字段(C#)
- 在运行时将一个byte 加载到Image中
- WCF服务参考不在其他PC上工作
- 无法将类型为“object {System.Collections.Generic.List }”的对象强制转换为ICollection
- Microsoft.Office.Interop是否可以安全地用于(文件转换)网站?
- 使用包含&符号的URL将XML加载到XDocument
- 如何限制FFMpeg CPU使用率?