0

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+.
Fernando
  • 29
  • 5
  • 1
    By "i would like edit the images already added to one product," do you mean let the user select a new file and overwrite the original file AND update the image in the UI? and what line does the error get thrown at? new Bitmap? b.Save? Image = b? – Tom Jun 09 '16 at 21:59
  • @TomA, yes, thats right. " do you mean let the user select a new file and overwrite the original file AND update the image in the UI?" I have the error on this line: b.Save(Path.Combine(Application.StartupPath, "Imagenes", nombre)); – Fernando Jun 09 '16 at 22:27

1 Answers1

1

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. 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. 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! If it is, set it to null there before disposing : pictureBox1.Image = null; !

For a solution deleting the old file see here

Community
  • 1
  • 1
TaW
  • 53,122
  • 8
  • 69
  • 111