Graphics DrawString参数无效
一个生成图片的ashx页面,执行到DrawString时就报错,重启iis后第一次或者第二次访问能正常生成图片,后续的访问执行到DrawString时就报错了。什么问题?
framework版本是2.0的,系统win2003
[ArgumentException: 参数无效。]
System.Drawing.Graphics.CheckErrorStatus(Int32 status) +1048569
System.Drawing.Graphics.DrawString(String s, Font font, Brush brush, RectangleF layoutRectangle, StringFormat format) +211
System.Drawing.Graphics.DrawString(String s, Font font, Brush brush, Single x, Single y) +53
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +406
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +76
public void ProcessRequest(HttpContext context)Graphics ?DrawString 参数无效
{ Bitmap nbitmap = new Bitmap(1000, 1000);
Graphics g = Graphics.FromImage(nbitmap);
Font font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Italic);
Brush brush = Brushes.Black;
g.DrawString("测试字符串", font, brush, 10, 10);/////
g.Dispose();
font.Dispose();
brush.Dispose();
nbitmap.Save(context.Server.MapPath("~/upload/cert" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg"));
nbitmap.Dispose();
}
Font font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Italic);
Brush brush = Brushes.Black;
g.DrawString("测试字符串", font, brush, 10, 10);/////
font.Dispose();
brush.Dispose();
g.Dispose();
//font.Dispose(),brush.Dispose()删除试试
nbitmap.Save(context.Server.MapPath("~/upload/cert" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg"));
nbitmap.Dispose();
[解决办法]
测试过有效的代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
string str = Server.MapPath("~/upload/test.jpg");
System.Drawing.Image myImage = System.Drawing.Image.FromFile(str);
Bitmap map = new Bitmap(myImage);
myImage.Dispose();
Graphics graphics = Graphics.FromImage(map);
graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
SolidBrush brush = new SolidBrush(Color.Red);
PointF P = new PointF(100, 100);
Font font = new Font("宋体", 40);
graphics.DrawString("guwei4037", font, brush, P);
map.Save(str.Substring(0, str.LastIndexOf("\") + 1) + "new" + str.Substring(str.LastIndexOf("\") + 1, str.LastIndexOf(".") - str.LastIndexOf("\") - 1) + str.Substring(str.LastIndexOf("."), str.Length - str.LastIndexOf(".")), ImageFormat.Jpeg);
font.Dispose();
graphics.Dispose();
}
catch { }
}
}