-1

I have some task - resize image if height or width >500px. I try this code.

But when I choosed image I have error like

NewImage.Save(path);

В GDI+ error of the general form.

private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog fdlg = new OpenFileDialog();
            fdlg.Multiselect = true;
            if (fdlg.ShowDialog() == DialogResult.OK)
            {
                for (int i = 0; i < fdlg.FileNames.Length; i++)
                {
                    string file = fdlg.FileNames[i];
                    string path = System.IO.Path.GetFullPath(file);
                    System.Drawing.Image img = System.Drawing.Image.FromFile(path);
                    if (img.Width > 500 || img.Height > 500)
                    {
                        int currW = img.Width;
                        int currH = img.Height;
                        int realWPer = 500 * 100 / currW;
                        int realHPer = 500 * 100 / currH;
                        int realW = currW / 100 * realWPer; // new width
                        int realH = currH / 100 * realHPer; // new height

                        Image NewImage = resizeImage(img, new Size(realW, realH));
                        NewImage.Save(path);
                    }
                }
            }
        }

public static Image resizeImage(Image imgToResize, Size size)
{
   return (Image)(new Bitmap(imgToResize, size));
}
artm
  • 8,554
  • 3
  • 26
  • 43
bigjoy10
  • 55
  • 1
  • 8

1 Answers1

2

You haven't posted the error message so one can only guess what may be wrong, I'd guess you get an error that you are trying to access a locked file.

You are trying to save the new image over the old image which is still open. You never close/dispose the img so it's still open when you try to save the new image using the same path as the old

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236