0

Using Visual Studio C#. I want to save the image inside my PictureBox as a .png using SaveFileDialog, but whenever I try to, I keep getting NullReferenceException at the last line. I can't seem to figure out what's causing this and how to fix it.

private void button_Save_Click(object sender, EventArgs e)
    {
        SaveFileDialog sfd = new SaveFileDialog();
        sfd.Filter = "PNG(*.PNG)|*.png";

        if (sfd.ShowDialog() == DialogResult.OK)
            pictureBox.Image.Save(sfd.FileName, ImageFormat.Png);
    }

1 Answers1

-1

The reason that you're getting a NullReferenceException is because pictureBox.Image.Save(...) is actually trying to use the image in the picture box to save to your computer, but there is no image in the picturebox to save, resulting in the error.

What I think you're trying to accomplish is putting the image inside the picturebox. And if that's the case, I'd recommend using the following:

private void button_Save_Click(object sender, EventArgs e)
{
    var fd = new OpenFileDialog { Filter = @"PNG(*.PNG)|*.png" };

    if (fd.ShowDialog() == DialogResult.OK)
        pictureBox.Image = Image.FromFile(fd.FileName);
}
Joseph
  • 5,070
  • 1
  • 25
  • 26