} private void CreateImage(string checkCode) { System.Drawing.Bitmap image = new System.Drawing.Bitmap(Convert.ToInt32(Math.Ceiling((decimal)(checkCode.Length * 14))), 22); Graphics g = Graphics.FromImage(image); try {
Random random = new Random(); g.Clear(Color.AliceBlue);
for (int i = 0; i < 25; i++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } Font font = new System.Drawing.Font("Comic Sans MS", 12, System.Drawing.FontStyle.Bold); System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true); g.DrawString(checkCode, font, new SolidBrush(Color.Red), 2, 2); for (int i = 0; i < 100; i++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next())); } g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); Response.ClearContent(); Response.ContentType = "image/Gif"; Response.BinaryWrite(ms.ToArray()); } finally { g.Dispose(); image.Dispose(); } } public string CreateRandomCode(int codeCount) { string allChar = "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[] allCharArray = allChar.Split(','); string randomCode = ""; int temp = -1; Random rand = new Random(); for (int i = 0; i < codeCount; i++) { if (temp != -1) { rand = new Random(i * temp * ((int)DateTime.Now.Ticks)); } int t = rand.Next(36); if (temp != -1 && temp == t) { return CreateRandomCode(codeCount); } temp = t; randomCode += allCharArray[t]; } return randomCode; }调用的时候 <img src="code.aspx" border="0" />最后在加上一个点击切换就更好了。。 方法如下:<img src= "code.aspx" alt= "看不清" style= "cursor:hand" onclick="this.src= 'code.aspx?date=new Date() ' "/> 这些东西可以下载个项目 抄袭项目里的。 这样比较好!
我自己刚做了一个using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using System.Drawing; using System.Drawing.Imaging;public partial class ValidateCode : System.Web.UI.Page { private int codeLen = 4;//验证码长度 private int fineness = 85;//图片清晰度 private int imgWidth = 48;//图片宽度 private int imgHeight = 24;//图片高度 private string fontFamily = "Times New Roman";//字体名称 private int fontSize = 14;//字体大小 private int posX = 0;//绘制起始坐标X private int posY = 0;//绘制坐标Y protected void Page_Load(object sender, EventArgs e) { string validateCode = CreateValidateCode();//生成验证码 Bitmap bitmap = new Bitmap(imgWidth, imgHeight);//生成BitMap图像 DisturbBitmap(bitmap);//图像背景 DrewValidateCode(bitmap, validateCode);//绘制验证码图像 bitmap.Save(Response.OutputStream, ImageFormat.Gif);//保存图像,等待输出 } private string CreateValidateCode()//生成验证码 { string validateCode = ""; Random random = new Random();//随机数对象 for (int i = 0; i < codeLen; i++)//循环生成每位数值 { int n = random.Next(10);//数字 validateCode += n.ToString(); } Session["vcode"] = validateCode;//保存验证码 return validateCode;//返回验证码 } private void DisturbBitmap(Bitmap bitmap)//图像背景 { Random random = new Random();//通过随机数生成 for (int i = 0; i < bitmap.Width; i++)//通过循环嵌套,逐个像素点生成 { for (int j = 0; j < bitmap.Height; j++) { if (random.Next(90) <= fineness) { bitmap.SetPixel(i, j, Color.LightGray); } } } } private void DrewValidateCode(Bitmap bitmap, string validateCode)//绘制验证码图像 { Graphics g = Graphics.FromImage(bitmap);//获取绘制器对象 Font font = new Font(fontFamily, fontSize, FontStyle.Bold);//设置绘制字体 g.DrawString(validateCode, font, Brushes.Black, posX, posY);//绘制验证码图像 } }
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Drawing;namespace EIMS
{
public partial class CheckCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CreateCheckCodeImage(GenerateCheckCode());
}
private string GenerateCheckCode() //绘制4个随机数或字母
{
int number;
char code;
string checkCode = String.Empty; Random random = new Random(); for (int i = 0; i < 4; i++)
{
number = random.Next(); if (number % 2 == 0)
code = (char)('0' + (char)(number % 10));
else
code = (char)('A' + (char)(number % 26)); checkCode += code.ToString();
} Response.Cookies.Add(new HttpCookie("CheckCode", checkCode)); return checkCode;
}
private void CreateCheckCodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return; System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
Graphics g = Graphics.FromImage(image); try
{
//生成随机生成器
Random random = new Random(); //清空图片背景色
g.Clear(Color.White); //画图片的背景噪音线
for (int i = 0; i < 2; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height); g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
} Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold));
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, font, brush, 2, 2); //画图片的前景噪音点
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next()));
} //画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
}
}
再在要添加验证码处添加<asp:Image ID="Image1" runat="server" Height="27px" Width="77px"
imageurl="CheckCode.aspx"/>
基本就是一个页面专门负责在服务器端生成一张验证码图片(.aspx或者.ashx都行)
然后在需要显示的页面用一个<img src="verifyCode.aspx" border="0" />引用就了
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["code"] != null)
{
if (Session["code"] != Request.QueryString["code"].ToString())
{
Response.Write("codewrong");
Response.End();
return;
}
}
Session["code"] = GetCode(4); ;
CreateImage(Session["code"].ToString());
}
public string GetCode(int count)
{
string str = "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,";
str += str.ToUpper();
str += "0,1,2,3,4,5,6,7,8,9";
string[] strs = str.Split(',');
string code = "";
Random rd = new Random();
for (int i = 0; i < count; i++)
{
code += strs[rd.Next(strs.Length)];
}
return code;
}
public void CreateImage(string code)
{
Bitmap bit = new Bitmap(50, 20);
Graphics g = Graphics.FromImage(bit);
SolidBrush solid = new SolidBrush(Color.Magenta);
g.Clear(Color.Snow);
MemoryStream ms = new MemoryStream();
g.DrawString(code, new Font("宋体", 14, FontStyle.Strikeout), solid, new PointF(0, 0));
bit.Save(ms, ImageFormat.Gif);
Response.ContentType = "image/gif";
Response.BinaryWrite(ms.ToArray());
Response.End();
}
}调用时 设置img src为产生这个验证码的页面就OK
{
public ValidCode()
{
}
private string GenerateCheckCode()
{
int number;
char code;
string checkCode = String.Empty;
System.Random random = new Random();
for (int i = 0; i < 5; i++)
{
number = random.Next();
if (number % 2 == 0)
code = (char)('0' + (char)(number % 10));
else
code = (char)('A' + (char)(number % 26)); checkCode += code.ToString();
}
// HttpContext.Current.Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
return checkCode;
}
/// <summary>
/// 生成验证码图片
/// </summary>
public void CreateCheckCodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return; System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
Graphics g = Graphics.FromImage(image); try
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的背景噪音线
for (int i = 0; i < 25; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
} Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, font, brush, 2, 2); //画图片的前景噪音点
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ContentType = "image/Gif";
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
public void ValidateCode(string VNum)
{
Bitmap validateimage;
Graphics g;
validateimage = new Bitmap(50, 20, PixelFormat.Format24bppRgb);
g = Graphics.FromImage(validateimage); g.DrawString(VNum, new Font("Comic Sans MS", 12), new SolidBrush(Color.White), new PointF(3, 0));
g.FillRectangle(new LinearGradientBrush(new Point(0, 0), new Point(110, 20), Color.FromArgb(0, 0, 0, 0), Color.FromArgb(255, 255, 60, 40)), 0, 0, 120, 30);
g.Save();
MemoryStream ms = new MemoryStream();
validateimage.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ContentType = "image/gif";
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
HttpContext.Current.Response.End();
}
/// 生成随机数
public string MakeValidateCode()
{
char[] s = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
string num = "";
Random r = new Random();
for (int i = 0; i < 4; i++)
{
num += s[r.Next(0, s.Length)].ToString();
}
return num;
}
建立个页面 命名 code.aspx
protected void Page_Load(object sender, EventArgs e)
{
//先产生数字串
string checkCode = this.CreateRandomCode(6);
//用session保存
Session["CheckCode"] = checkCode;
//作图
CreateImage(checkCode);
}
private void CreateImage(string checkCode)
{
System.Drawing.Bitmap image = new System.Drawing.Bitmap(Convert.ToInt32(Math.Ceiling((decimal)(checkCode.Length * 14))), 22);
Graphics g = Graphics.FromImage(image);
try
{
Random random = new Random();
g.Clear(Color.AliceBlue);
for (int i = 0; i < 25; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
} Font font = new System.Drawing.Font("Comic Sans MS", 12, System.Drawing.FontStyle.Bold);
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, font, new SolidBrush(Color.Red), 2, 2);
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next()));
} g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
} public string CreateRandomCode(int codeCount)
{
string allChar = "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[] allCharArray = allChar.Split(',');
string randomCode = "";
int temp = -1; Random rand = new Random();
for (int i = 0; i < codeCount; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(36);
if (temp != -1 && temp == t)
{
return CreateRandomCode(codeCount);
}
temp = t;
randomCode += allCharArray[t];
}
return randomCode;
}调用的时候 <img src="code.aspx" border="0" />最后在加上一个点击切换就更好了。。
方法如下:<img src= "code.aspx" alt= "看不清" style= "cursor:hand" onclick="this.src= 'code.aspx?date=new Date() ' "/>
这些东西可以下载个项目 抄袭项目里的。 这样比较好!
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;public partial class ValidateCode : System.Web.UI.Page
{
private int codeLen = 4;//验证码长度
private int fineness = 85;//图片清晰度
private int imgWidth = 48;//图片宽度
private int imgHeight = 24;//图片高度
private string fontFamily = "Times New Roman";//字体名称
private int fontSize = 14;//字体大小
private int posX = 0;//绘制起始坐标X
private int posY = 0;//绘制坐标Y protected void Page_Load(object sender, EventArgs e)
{
string validateCode = CreateValidateCode();//生成验证码
Bitmap bitmap = new Bitmap(imgWidth, imgHeight);//生成BitMap图像
DisturbBitmap(bitmap);//图像背景
DrewValidateCode(bitmap, validateCode);//绘制验证码图像
bitmap.Save(Response.OutputStream, ImageFormat.Gif);//保存图像,等待输出
} private string CreateValidateCode()//生成验证码
{
string validateCode = "";
Random random = new Random();//随机数对象
for (int i = 0; i < codeLen; i++)//循环生成每位数值
{
int n = random.Next(10);//数字
validateCode += n.ToString();
}
Session["vcode"] = validateCode;//保存验证码
return validateCode;//返回验证码
} private void DisturbBitmap(Bitmap bitmap)//图像背景
{
Random random = new Random();//通过随机数生成
for (int i = 0; i < bitmap.Width; i++)//通过循环嵌套,逐个像素点生成
{
for (int j = 0; j < bitmap.Height; j++)
{
if (random.Next(90) <= fineness)
{
bitmap.SetPixel(i, j, Color.LightGray);
}
}
}
} private void DrewValidateCode(Bitmap bitmap, string validateCode)//绘制验证码图像
{
Graphics g = Graphics.FromImage(bitmap);//获取绘制器对象
Font font = new Font(fontFamily, fontSize, FontStyle.Bold);//设置绘制字体
g.DrawString(validateCode, font, Brushes.Black, posX, posY);//绘制验证码图像
}
}
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;public partial class validate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!this.IsPostBack)
{
this.GenImg(this.GetCode(4));
}
}
//产生随机字符串
private string GetCode(int num)
{
string[] source={"1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","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;
} //生成图片
private void GenImg(string code)
{
Random rd = new Random();
Bitmap myPalette = new Bitmap(120, 60); //定义一个画板
Graphics gh = Graphics.FromImage(myPalette); //在画板上定义绘图的实例
Rectangle rc = new Rectangle(0, 0, 120, 60); //定义一个矩形
String picPath = Server.MapPath("pic/bg" + rd.Next(1,4).ToString().Trim() + ".jpg" );
Bitmap imagefile = (Bitmap)System.Drawing.Image.FromFile(picPath, true); //得到一张位图
TextureBrush texture = new TextureBrush(imagefile); //以图片建立绘图刷
Color[] fontcolor = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Red, Color.Brown, Color.DarkCyan, Color.Purple }; //定义 8 种颜色
String[] fontname = { "Verdana", "System", "Comic Sans MS", "Arial", "宋体" }; //定义 5 种字体
Font myfont; //字体定义
SolidBrush mybrush; //画笔定义
gh.FillRectangle(texture, rc);//使用绘图刷填充矩形,到此得到图片背景 for (short i = 0; i <= code.Length - 1; i++)
{
myfont = new Font(fontname[rd.Next(0, 5)],30,FontStyle.Italic); //随机字体,42号,斜体
mybrush = new SolidBrush(fontcolor[rd.Next(0, 8)]); //随机颜色
gh.DrawString(code.Substring(i,1) , myfont, mybrush, 3 + (i * 23),rd.Next(1,8));//在矩形内画出字符串
}
然后给要验证的地方加一个img.大致就这样的吧。
判断的时候把用户输入的全部转换大写,