开发者

Parameter is not valid exception when saving image in winform

I am getting a parameter is not valid exc开发者_Go百科eption..While saving the image

Here is my code to save the image

if (!File.Exists(pictureBox1.Tag.ToString()))
{
    Image image = pictureBox1.Image;
    image.Save(pictureBox1.Tag.ToString(), ImageFormat.Jpeg);
}
else
{
    string delStr = pictureBox1.Tag.ToString();
    pictureBox1.Image.Dispose();
    File.Delete(delStr);
    Image image = pictureBox1.Image;
    image.Save(delStr, ImageFormat.Jpeg);
    pictureBox1.Image = Image.FromFile(delStr);
}


In your else branch, you start by calling Dispose() on your Image, then you try to save it. That can't possibly work, because:

The Dispose method leaves the Image in an unusable state.

Maybe you wanted to do:

string delStr = pictureBox1.Tag.ToString();
File.Delete(delStr);
Image image = pictureBox1.Image;
image.Save(delStr, ImageFormat.Jpeg);
image.Dispose();
pictureBox1.Image = Image.FromFile(delStr);

But that's still reloading the Image from the very file it has just been saved to, so it's not very useful. You might want to try something like:

string filename = pictureBox1.Tag.ToString();
if (File.Exists(filename) {
    File.Delete(filename);
}
pictureBox1.Image.Save(filename, ImageFormat.Jpeg);

But then again, Image.Save() will overwrite the file anyway... So you only need to do:

pictureBox1.Image.Save(pictureBox1.Tag.ToString(), ImageFormat.Jpeg);


Am I seeing correctly? Are you disposing the image before saving it? If so here is your problem:

pictureBox1.Image.Dispose(); // THIS !!!!!! Just remove this line or move it to after save
Image image = pictureBox1.Image;
image.Save(delStr, ImageFormat.Jpeg);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜