HTML的代码:
- <!--
- Document : ASP.NET用一般处理程序生成验证码
- Created on : 2010-6-3 17:04
- Author : lostwolf
- -->
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title></title>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
- <script type="text/javascript">
- function change() {
- var imgNode = document.getElementById("vimg");
- imgNode.src = "WaterMark.ashx?t=" + (new Date()).valueOf(); // 这里加个时间的参数是为了防止浏览器缓存的问题
- }
- </script>
- </head>
- <body>
- <img src="WaterMark.ashx" id="vimg" alt="" /><input type="button" value="换一张图片" onclick="change()" />
- </body>
- </html>
<!-- Document : ASP.NET用一般处理程序生成验证码 Created on : 2010-6-3 17:04 Author : lostwolf--><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <script type="text/javascript"> function change() { var imgNode = document.getElementById("vimg"); imgNode.src = "WaterMark.ashx?t=" + (new Date()).valueOf(); // 这里加个时间的参数是为了防止浏览器缓存的问题 } </script> </head> <body> <img src="WaterMark.ashx" id="vimg" alt="" /><input type="button" value="换一张图片" onclick="change()" /> </body></html>
一般处理程序WaterMark.ashx的代码:
- <%@ WebHandler Language="C#" Class="WaterMark" %>
- using System;
- using System.Web;
- using System.Drawing;
- using System.Drawing.Drawing2D;
- using System.Web.SessionState;
- public class WaterMark : IHttpHandler, IRequiresSessionState // 要使用session必须实现该接口,记得要导入System.Web.SessionState命名空间
- {
- public void ProcessRequest(HttpContext context)
- {
- string checkCode = GenCode(5); // 产生5位随机字符
- context.Session["Code"] = checkCode; //将字符串保存到Session中,以便需要时进行验证
- System.Drawing.Bitmap image = new System.Drawing.Bitmap(70, 22);
- Graphics g = Graphics.FromImage(image);
- try
- {
- //生成随机生成器
- Random random = new Random();
- //清空图片背景色
- g.Clear(Color.White);
- // 画图片的背景噪音线
- int i;
- for (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.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);
- //画图片的前景噪音点
- 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);
- context.Response.ClearContent();
- context.Response.ContentType = "image/Gif";
- context.Response.BinaryWrite(ms.ToArray());
- }
- finally
- {
- g.Dispose();
- image.Dispose();
- }
- }
- /// <summary>
- /// 产生随机字符串
- /// </summary>
- /// <param name="num">随机出几个字符</param>
- /// <returns>随机出的字符串</returns>
- private string GenCode(int num)
- {
- string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//"的一是在不了有和人这中大为上个国我以要他时来用们生到作地于出就分对成会可主发年动同工也能下过子说产种面而方后多定行学法所民得经十三之进着等部度家电力里如水化高自二理起小物现实加量都两体制机当使点从业本去把性好应开它合还因由其些然前外天政四日那社义事平形相全表间样与关各重新线内数正心反你明看原又么利比或但质气第向道命此变条只没结解问意建月公无系军很情者最立代想已通并提直题党程展五果料象员革位入常文总次品式活设及管特件长求老头基资边流路级少图山统接知较将组见计别她手角期根论运农指几九区强放决西被干做必战先回则任取据处队南给色光门即保治北造百规热领七海口东导器压志世金增争济阶油思术极交受联什认六共权收证改清己美再采转更单风切打白教速花带安场身车例真务具万每目至达走积示议声报斗完类八离华名确才科张信马节话米整空元况今集温传土许步群广石记需段研界拉林律叫且究观越织装影算低持音众书布复容儿须际商非验连断深难近矿千周委素技备半办青省列习响约支般史感劳便团往酸历市克何除消构府称太准精值号率族维划选标写存候毛亲快效斯院查江型眼王按格养易置派层片始却专状育厂京识适属圆包火住调满县局照参红细引听该铁价严";
- char[] chastr = str.ToCharArray();
- // 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();
- int i;
- for (i = 0; i < num; i++)
- {
- //code += source[rd.Next(0, source.Length)];
- code += str.Substring(rd.Next(0, str.Length), 1);
- }
- return code;
- }
- public bool IsReusable
- {
- get
- {
- return false;
- }
- }
- }
方法一:
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;
public partial class Background_Code : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string str2 = GenerateCheckCode();
CreateCheckCodeImage(str2);
}
/// <summary>
/// 产生数
/// </summary>
/// <returns></returns>
public string GenerateCheckCode()
{
Random temp = new Random();
string str1 = "0123456789abcdefghijklmnopqrstuvwxyz";
string str = "";
for (int i = 0; i < 4; i++)
{
str = str + str1.Substring(temp.Next(36), 1);
}
Session["Val"] = str;
return str;
}
/// <summary>
/// 产生图片
/// </summary>
/// <param name="num">随机产生的数字字符串</param>
public void CreateCheckCodeImage(string num)
{
if (num == null || num.Trim() == String.Empty)
return;
System.Drawing.Bitmap img = new System.Drawing.Bitmap((int)Math.Ceiling((num.Length * 12.5)), 22);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(img);
try
{
Random ra = new Random();
g.Clear(System.Drawing.Color.White);
for (int j = 0; j < 2; j++)
{
int x1 = ra.Next(img.Width);
int x2 = ra.Next(img.Width);
int y1 = ra.Next(img.Height);
int y2 = ra.Next(img.Height);
g.DrawLine(new System.Drawing.Pen(System.Drawing.Color.Black), x1, y1, x2, y2);
}
System.Drawing.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 System.Drawing.Rectangle(0, 0, img.Width, img.Height), System.Drawing.Color.Blue, System.Drawing.Color.DarkRed, 1.2f, true);
g.DrawString(num, font, brush, 2, 2);
for (int k = 0; k < 100; k++)
{
int x = ra.Next(img.Width);
int y = ra.Next(img.Height);
img.SetPixel(x, y, System.Drawing.Color.FromArgb(ra.Next()));
}
//图片边缘
g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Silver), 0, 0, img.Width - 1, img.Height - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
img.Dispose();
}
}
}
新建一个网页 写个img标签 src=上面的路径就可以了
方法2:
using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
public partial class images_code : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string chkCode = string.Empty;
//颜色列表,用于验证码、噪线、噪点
Color[] color ={ Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange,Color.Brown, Color.DarkBlue };
//字体列表,用于验证码
string[] font ={ "Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh","PMingLiU", "Impact" };
//验证码的字符集,去掉了一些容易混淆的字符
char[] character ={ '2', '3', '4', '5', '6', '8', '9', 'A', 'B', 'C', 'D', 'E','F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
Random rnd = new Random();
//生成验证码字符串
for (int i = 0; i < 4; i++)
{
chkCode += character[rnd.Next(character.Length)];
}
//保存验证码的Cookie
HttpCookie anycookie = new HttpCookie("validateCookie");
anycookie.Values.Add("ChkCode", chkCode);
HttpContext.Current.Response.Cookies["validateCookie"].Values["ChkCode"] = chkCode;
Bitmap bmp = new Bitmap(80,20);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.White);
//画噪线
for (int i = 0; i < 3; i++)
{
int x1 = rnd.Next(80);
int y1 = rnd.Next(20);
int x2 = rnd.Next(80);
int y2 = rnd.Next(20);
Color clr = color[rnd.Next(color.Length)];
g.DrawLine(new Pen(clr), x1, y1, x2, y2);
}
//画验证码字符串
for (int i = 0; i < chkCode.Length; i++)
{
string fnt = font[rnd.Next(font.Length)];
Font ft = new Font(fnt, 11);
Color clr = color[rnd.Next(color.Length)];
g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 20 + 6, (float)2);
}
//画噪点
for (int i = 0; i < 50; i++)
{
int x = rnd.Next(bmp.Width);
int y = rnd.Next(bmp.Height);
Color clr = color[rnd.Next(color.Length)];
bmp.SetPixel(x, y, clr);
}
//清除该页输出缓存,设置该页无缓存
Response.Buffer = true;
Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0);
Response.Expires = 0;
Response.CacheControl = "no-cache";
Response.AppendHeader("Pragma", "No-Cache");
//将验证码图片写入内存流,并将其以"image/Png" 格式输出
MemoryStream ms = new MemoryStream();
try
{
bmp.Save(ms, ImageFormat.Png);
Response.ClearContent();
Response.ContentType = "image/Png";
Response.BinaryWrite(ms.ToArray());
}
finally
{
bmp.Dispose(); //显式释放资源
g.Dispose();
}
}
}