Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception: Parameter is not valid (on passing new image to pictureBox)

Tags:

c#

image

dispose

I already had an image inside PictureBox control, and now I want to pass a new one to it.

What happens, is that allpication Disposes (and I catch an exception: "Parameter is not valid").

This is my code:

            using (Image img = Image.FromFile(open.FileName))
            {
                part.Picture = img;
                pictureBox1.InitialImage = null;
                pictureBox1.Image = img;
            }    

So when the code goes out of the method, it goes streight to Displose of this and main form. I catch the exception only on line where Form1 was started. On this one there is no excpetions what so ever. It must be something wrong while pictureBox is painting (inside Paint event), but I am not surbsribed to it.

I really dont have any more clue how to salve this issue. I have even tried to use to clear all resources (by calling garbage collection), but nothing seems to work.


One more thing: "part" is a reference of the List, so when I try to Delete the current image (to replace it with a new one) I got another exception, like:

"The process cannot access the file because it is being used by another process".


Does this has something to do with the 1st exception (when new image is not painted in pictureBox)?

like image 232
Mitja Bonca Avatar asked Oct 01 '12 20:10

Mitja Bonca


2 Answers

As Reed noted, the Image you are pulling from open.Filename is being disposed once you exit the using() statement. Your picturebox is still referencing this image in memory, so when it is disposed, you lose what was stored in your picturebox too.

What you really need is a unique copy of the image you are pulling.

    using (Image sourceImg = Image.FromFile(open.Filename))
    {
        Image clonedImg = new Bitmap(sourceImg.Width, sourceImg.Height, PixelFormat.Format32bppArgb);
        using (var copy = Graphics.FromImage(clonedImg))
        {
            copy.DrawImage(sourceImg, 0, 0);
        }
        pictureBox1.InitialImage = null;
        pictureBox1.Image = clonedImg;
    }

This way, your file will be unlocked as soon as you exit this block, and you'll keep a unique copy of your image in the picturebox.

like image 186
MadHenchbot Avatar answered Nov 11 '22 13:11

MadHenchbot


The problem is that, after this code executes, pictureBox1.Image is referring to an Image which has been disposed.

If you do not wrap the Image creation in a using, it should correct your issue.

Image img = Image.FromFile(open.FileName);
part.Picture = img;
pictureBox1.InitialImage = null;
pictureBox1.Image = img; // You can't dispose of this, or it won't be valid when PictureBox uses it!
like image 26
Reed Copsey Avatar answered Nov 11 '22 12:11

Reed Copsey