using System; using System.Drawing; /// <summary> /// CheckCode 的摘要说明 /// </summary> public class CheckCode { public CheckCode() { // // TODO: 在此处添加构造函数逻辑 // } private static string GenCode(int num) { string[] source ={"0","1","2","3","4","5","6","7","8","9", "A","B","C","D","E","F","G","H","I","J","K","L","M","N", "O","P","Q","R","S","T","U","V","W","X","Y","Z"}; string code = ""; Random rd = new Random(); for (int i = 0; i < num; i++) { code += source[rd.Next(0, source.Length)]; } return code; } public static Bitmap getCode() { string code = GenCode(4); Random ran = new Random(); string picRoot = System.Web.HttpContext.Current.Server.MapPath("~/"); string backRoot = picRoot + "//images//codebg//bg" + ran.Next(0, 9).ToString() + ".jpg";//随机读取一张背景 if (code.Length <= 0)//如果指定的字符串长度少于1就退出 { return null; } int width = 80;//图片的长度 //int heigth = 20;//图片的宽度 //Bitmap img=new Bitmap(width,heigth);//实例化一张图片 Bitmap img = new Bitmap(Image.FromFile(backRoot)); Graphics mygrp = Graphics.FromImage(img);//把图片传给Graphics对象 Font chrfont = new Font("宋体", 16, FontStyle.Bold);//设置图片的字体 char[] codeChr = code.ToCharArray();//把验证码字符串打散成单个字符,以便一个个设置颜色 float heigChr = 0.0F;//指定与字符顶端的距离(即Y轴坐标) for (int k = 0; k < codeChr.Length; k++) { float chrwidth = width * k / 4 - 2;//指定当前字符与左边的距离(即X轴坐标) Color cor = Color.FromArgb(20 + ran.Next(80), 20 + ran.Next(80), +20 + ran.Next(80));//随机生成当前字母的颜色R、G、B都在20-130间抖动 SolidBrush chrbsh = new SolidBrush(cor);//设置一个绘制文字的笔刷,颜色是刚才生成的 mygrp.DrawString(codeChr[k].ToString(), chrfont, chrbsh, chrwidth, heigChr, new StringFormat());//绘制这个字符 } System.Web.HttpContext.Current.Session["theCheckCode"] = code; return img; } } 使用: protected void Page_Load(object sender, EventArgs e) { Response.ContentType = "application/octet-stream"; Bitmap bp = CheckCode.getCode(); bp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); Response.End(); } 效果: