Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

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+.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...