简体   繁体   English

覆盖C#中的图片图片框

[英]Overwrite image picturebox in C#

I'm doing one application, i add a picturebox to add image to some products, i have one question, i would like edit the images already added to one product, how can i do that? 我正在做一个应用程序,我添加了一个图片框来将图像添加到某些产品中,我有一个问题,我想编辑已经添加到一个产品中的图像,我该怎么做? This is my actually code. 这是我的实际代码。

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;

    }
}

But when i try to replace the image i got this error: 但是,当我尝试替换图像时,出现此错误:

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

Additional information: Error generoc in e GDI+.

This is a common issue. 这是一个普遍的问题。

The documentation says: 文件说:

Saving the image to the same file it was constructed from is not allowed and throws an exception. 不允许将图像保存到构造该图像的相同文件中,并引发异常。

There are two options. 有两种选择。 One is to delete the file before writing it. 一种是在写入文件之前将其删除。

The other is to use a Stream to write it. 另一种是使用Stream来编写它。 I prefer the latter..: 我更喜欢后者..:

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);

Note that saving jpeg files often achieves better quality if you take control of encoding options. 请注意,如果您控制编码选项,则保存jpeg文件通常可以获得更好的质量。 Use this overload for this.. 为此 ,请使用此重载

Also note that since we need to dispose of the image you need to make sure that it is not used anywhere, like in a PictureBox.Image ! 还要注意,由于我们需要处理图像,因此需要确保未在任何地方使用它,例如在PictureBox.Image If it is, set it to null there before disposing : pictureBox1.Image = null; 如果是,将其设置为null处置前有: pictureBox1.Image = null; !

For a solution deleting the old file see here 有关删除旧文件的解决方案,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM