簡體   English   中英

在C#中調整圖片大小並保存該圖片

[英]Resize image in c# and save this image

我有一些任務-如果高度或寬度> 500像素,請調整圖像大小。 我嘗試這段代碼。

但是當我選擇圖像時,我會遇到類似

NewImage.Save(path);

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

您尚未發布錯誤消息,因此只能猜測可能出了什么問題,我想您會收到一條錯誤消息,您正在嘗試訪問鎖定的文件。

您試圖將新圖像保存在仍然打開的舊圖像上。 您永遠不會關閉/處理img因此當您嘗試使用與舊路徑相同的路徑保存新圖像時,它仍然處於打開狀態

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM