生成Image发生异常,还不报错···里面有详细代码和错误截图
自己写的一个小Debug,如果直接Image img=new Bitmap()这种方式的话就没有问题,但一封装就出问题了...新人分数不多,在此谢过了public class _04VailCodeProduce : IHttpHandler,IRequiresSessionState
{
/// <summary>
/// 验证码字库
/// </summary>
private string[] strArr = { "a", "b", "c", "d", "e", "A", "B", "C", "D", "E" };
/// <summary>
/// 公共随机生成对象
/// </summary>
private Random ran = new Random();
private Image img;
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
CreateImg(63, 22, 4);
img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
#region 根据参数创建一张验证码图片+Image CreateImg(int weith, int height, int strLen)
/// <summary>
/// 根据参数创建一张验证码图片
/// </summary>
/// <param name="weith"></param>
/// <param name="height"></param>
/// <returns></returns>
void CreateImg(int width, int height, int strLen)
{
using (img = new Bitmap(width, height))
{
using (Graphics p = Graphics.FromImage(img))
{
//填充图片底色
p.FillRectangle(Brushes.White, 0, 0, img.Width - 2, img.Height - 2);
p.DrawString(CreateRandomStr(strLen), new Font("宋体", 10), Brushes.White,new PointF(5,5));
}
//return img;
}
}
#endregion
#region 根据长度生成随机字符串+string CreateRandomStr(int len)
/// <summary>
/// 根据长度生成随机字符串
/// </summary>
/// <param name="len"></param>
/// <returns></returns>
string CreateRandomStr(int len)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < len; i++)
{
//随机生成字库脚标,根据脚标获取其中的值,加入到sb中
sb.Append(strArr[ran.Next(0, strArr.Length)]);
}
return sb.ToString();
}
#endregion
--------------------编程问答-------------------- 这是没有蛋痛前的代码········
public void ProcessRequest(HttpContext context)--------------------编程问答-------------------- 没有人吗?? --------------------编程问答-------------------- using 误用了,下面的可行:
{
context.Response.ContentType = "image/jpeg";
//1.生成一张图片
using (Image img = new Bitmap(63, 22))
{
//2.建立画图对象
using (Graphics g = Graphics.FromImage(img))
{
//3.因为图片原来的颜色是黑,所以先涂成白色,四周留有边框
g.FillRectangle(Brushes.White, 1, 1, img.Width - 2, img.Height - 2);
//4.输出随机字
string vCode = RandomStr(4);
//5.存放到Session键值对中
context.Session["vCode"] = vCode;
//6.绘制到图片中
g.DrawString(vCode, new Font("微软雅黑", 10), Brushes.Black, new PointF(5, 5));
}
//输出
img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
void CreateImg(int width, int height, int strLen)
{
img = new Bitmap(width, height);
Graphics p = Graphics.FromImage(img);
//填充图片底色
p.FillRectangle(Brushes.White, 0, 0, img.Width - 2, img.Height - 2);
p.DrawString(CreateRandomStr(strLen), new Font("宋体", 10), Brushes.Black, new PointF(5, 5));
p.Dispose();
}
补充:.NET技术 , C#