调整c#中的图像大小并保存此图像

时间:2014-10-23 10:07:08

标签: c#

我有一些任务 - 如果高度或宽度> 500px,请调整图像大小。 我试试这段代码。

但是当我选择图像时,我有像

这样的错误

NewImage.Save(路径);

GDI +一般形式的错误。

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));
}

1 个答案:

答案 0 :(得分:2)

您尚未发布错误消息,因此您只能猜出可能出现的错误,我猜您会收到错误信息,说明您正在尝试访问锁定的文件。

您正尝试将新图像保存在仍然打开的旧图像上。您永远不会关闭/处置img,因此当您尝试使用与旧版本相同的路径保存新图像时它仍处于打开状态

相关问题