.net code:
public void ValidateCode() { // 在此处放置用户代码以初始化页面 string vnum; vnum = GetByRndNum(6); Response.ClearContent(); //需要输出图象信息 要修改HTTP头 Response.ContentType = "image/jpeg"; CreateValidateCode(vnum); } private void CreateValidateCode(string vnum) { Bitmap Img = null; Graphics g = null; Random random = new Random(); int gheight = vnum.Length * 15; Img = new Bitmap(gheight, 24); g = Graphics.FromImage(Img); Font f = new Font("宋体", 14, FontStyle.Bold); //Font f = new Font("宋体", 9, FontStyle.Bold); g.Clear(Color.White);//设定背景色 Pen blackPen = new Pen(ColorTranslator.FromHtml("#BCBCBC"), 3); for (int i = 0; i < 128; i++)// 随机产生干扰线,使图象中的认证码不易被其它程序探测到 { int x = random.Next(gheight); int y = random.Next(20); int xl = random.Next(6); int yl = random.Next(2); g.DrawLine(blackPen, x, y, x + xl, y + yl); } SolidBrush s = new SolidBrush(ColorTranslator.FromHtml("#411464")); g.DrawString(vnum, f, s, 3, 3); //画边框 blackPen.Width = 1; g.DrawRectangle(blackPen, 0, 0, Img.Width - 1, Img.Height - 1); Img.Save(Response.OutputStream, ImageFormat.Jpeg); s.Dispose(); f.Dispose(); blackPen.Dispose(); g.Dispose(); Img.Dispose(); //Response.End(); } //-----------------给定范围获得随机颜色------------ Color GetByRandColor(int fc, int bc) { Random random = new Random(); if (fc > 255) fc = 255; if (bc > 255) bc = 255; //if(ac>255) ac=255; int r = fc + random.Next(bc - fc); int g = fc + random.Next(bc - fc); int b = fc + random.Next(bc - bc); Color rs = Color.FromArgb(r, g, b); return rs; } public string GetByRndNum(int VcodeNum) { string VNum = ""; Random rand = new Random(); for (int i = 0; i < VcodeNum; i++) { VNum += VcArray[rand.Next(0, 9)]; } Session["Code"] = VNum; return VNum; } private static readonly string[] VcArray = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };