保存图像时ASP.NET MVC错误

时间:2016-08-22 15:01:28

标签: c# asp.net-mvc bitmap save-image

我正在尝试在项目中的给定路径中保存我从Bitmap创建的图像,但是我收到此错误:for(auto it = myvec->begin(); it != myvec->end(); ++it) { //code here }

这是代码:

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

我该怎么做才能解决这个问题?

编辑:我不明白为什么我被投票,但是没问题。

1 个答案:

答案 0 :(得分:0)

Server.MapPath包裹你的路径,如:

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

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

并在评论中使用@stuartd之类的Path.Combine方法。