保存时ASP.NET MVC错误图像
问题描述:
我想救我从位图在我的项目给定路径创建的图像,但我得到这个错误:Additional information: A generic error occurred in GDI+.
保存时ASP.NET MVC错误图像
这是代码:
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);
我能做些什么来解决这个问题?
编辑:我不明白为什么我被downvoted,但确定。
答
包裹你的路径与Server.MapPath,如:
image.Save(HttpContext.Current.Server.MapPath(Path.Combine(path, name + ".png")), ImageFormat.Png);
获得绝对路径,而不是相对的。
和使用Path.Combine方法像@stuartd建议在评论中。
我建议你总是使用'Path.Combine'来结合路径,而不是只是连接字符串 - 因为除非'name'以斜杠开始,否则你会用'image.Save(“pathname.png “,ImageFormat.Png);'而不是'image.Save(”path/name.png“,ImageFormat.Png);' – stuartd