ASP.保存图像时出现.NET MVC错误

本文关键字:NET MVC 错误 保存 图像 ASP | 更新日期: 2023-09-27 18:03:38

我试图保存我从位图中创建的图像在我的项目中给定的路径,但我得到这个错误:Additional information: A generic error occurred in GDI+.

这是代码:

        public void SaveCaptchaImage(string name)
        {
            Bitmap image = new Bitmap(128, 64);
            string path = "/content/images";
            if (System.IO.File.Exists(path + name))
                System.IO.File.Delete(path + name);
            using (Pen myPen = new Pen(Color.Red, 5))
            using (Brush myBrush = new SolidBrush(Color.Silver))
            using (Font myFont = new Font("Arial", 16))
            using (Graphics graphObject = Graphics.FromImage(image))
            {
                graphObject.FillRectangle(myBrush, new Rectangle(0, 0, 128, 64));
                graphObject.DrawString(GetRandomCaptcha(), myFont, myBrush, new Point(20, 20));
                image.Save(path + name + ".png", ImageFormat.Png);
            }
            image.Dispose();
        }

异常出现在这一行:

image.Save(path + name + ".png", ImageFormat.Png);

我能做些什么来解决这个问题?

编辑:我不明白为什么我被否决了,但是好吧

ASP.保存图像时出现.NET MVC错误

用Server包裹路径。MapPath:

image.Save(HttpContext.Current.Server.MapPath(Path.Combine(path, name + ".png")), ImageFormat.Png);

获取绝对路径而不是相对路径。

并使用Path。