(200分)讨论各大论坛的验证码算法(在线等)
过几天再补加100分,请熟悉验证码算法的朋友帮忙介绍下,
谢谢。。。
--------------------编程问答-------------------- 关注中…………………… --------------------编程问答-------------------- 参考
参考
参考
参考
--------------------编程问答-------------------- 我的。随机使用不同的字体,并且随机transform,还有加了噪点
--------------------编程问答-------------------- 顶一下 --------------------编程问答-------------------- Random random = new Random();
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
namespace Shop
{
/// <summary>
/// Summary description for ValidateCode.
/// </summary>
public class ValidateCode : System.Web.UI.Page
{
/// <summary>
/// Validation Code generated fromt these charaters.
/// Note: l,L 1(number), o, O, 0(number) are removed
/// </summary>
private const string strValidateCodeBound = "abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ23456789";
private static string[] Fonts = new string[] { "Helvetica",
"Geneva",
"sans-serif",
"Verdana",
"Times New Roman",
"Courier New",
"Arial"
};
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
/// <summary>
/// event handler of page load
/// </summary>
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
string str_ValidateCode = GetRandomString(6);
Session["ValidateCode"] = str_ValidateCode;
CreateImage(str_ValidateCode);
}
}
/// <summary>
/// Generate random string
/// </summary>
private string GetRandomString(int int_NumberLength)
{
string valString = string.Empty;
Random theRandomNumber = new Random((int)DateTime.Now.Ticks);
for (int int_index = 0; int_index < int_NumberLength; int_index++)
valString += strValidateCodeBound[theRandomNumber.Next(strValidateCodeBound.Length - 1)].ToString();
return valString;
}
/// <summary>
/// Generate random Color
/// </summary>
private Color GetRandomColor()
{
Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
System.Threading.Thread.Sleep(RandomNum_First.Next(50));
Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);
int int_Red = RandomNum_First.Next(256);
int int_Green = RandomNum_Sencond.Next(256);
int int_Blue = (int_Red + int_Green > 400) ? 0 : 400 - int_Red - int_Green;
int_Blue = (int_Blue > 255) ? 255 : int_Blue;
return Color.FromArgb(int_Red, int_Green, int_Blue);
}
/// <summary>
/// Create Validation Code Image
/// </summary>
private void CreateImage(string str_ValidateCode)
{
int int_ImageWidth = str_ValidateCode.Length * 22;
Random newRandom = new Random();
Bitmap theBitmap = new Bitmap(int_ImageWidth + 6 , 38);
Graphics theGraphics = Graphics.FromImage(theBitmap);
theGraphics.Clear(Color.White);
drawLine(theGraphics, theBitmap, newRandom);
theGraphics.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, theBitmap.Width - 1, theBitmap.Height -1 );
for (int int_index = 0; int_index < str_ValidateCode.Length; int_index++)
{
Matrix X = new Matrix();
X.Shear((float)newRandom.Next(0,300)/1000 - 0.25f, (float)newRandom.Next(0,100)/1000 - 0.05f);
theGraphics.Transform = X;
string str_char = str_ValidateCode.Substring(int_index, 1);
System.Drawing.Drawing2D.LinearGradientBrush newBrush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, theBitmap.Width, theBitmap.Height), Color.Blue, Color.DarkRed, 1.2f, true);
Point thePos = new Point(int_index * 21 + 1 + newRandom.Next(3), 1 + newRandom.Next(13));
Font theFont = new Font(Fonts[newRandom.Next(Fonts.Length -1)], newRandom.Next(14,18), FontStyle.Bold);
theGraphics.DrawString(str_char, theFont, newBrush, thePos);
}
drawPoint(theBitmap, newRandom);
MemoryStream ms = new MemoryStream();
theBitmap.Save(ms, ImageFormat.Png);
Response.ClearContent();
Response.ContentType = "image/Png";
Response.BinaryWrite(ms.ToArray());
theGraphics.Dispose();
theBitmap.Dispose();
Response.End();
}
/// <summary>
/// Draw Line for noise
/// </summary>
private void drawLine(Graphics gfc,Bitmap img, Random ran)
{
for (int i = 0; i < 10; i++)
{
int x1 = ran.Next(img.Width);
int y1 = ran.Next(img.Height);
int x2 = ran.Next(img.Width);
int y2 = ran.Next(img.Height);
gfc.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
}
/// <summary>
/// Draw Point for noise
/// </summary>
private void drawPoint(Bitmap img, Random ran)
{
for (int i = 0; i < 30; i++)
{
int x = ran.Next(img.Width);
int y = ran.Next(img.Height);
img.SetPixel(x,y,Color.FromArgb(ran.Next()));
}
}
}
}
Bitmap --------------------编程问答-------------------- 验证码算法?
不是几乎都一样吗 --------------------编程问答-------------------- ding... --------------------编程问答-------------------- public class VerificationCode : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//生成随机的字符串
string randomString = GetRandomString(4);
//将生成的字符串保存到数据库中
BoBoContext.Current.Session["Verification_Code"] = randomString;
//生成验证码图片
GenerateVerificationCodeImage(randomString, context);
}
public bool IsReusable
{
get
{
return false;
}
}
/// <summary>
/// 得到随机字符串,长度自己定义
/// </summary>
/// <param name="len">长度</param>
/// <returns>指定长度的随机字符串</returns>
private string GetRandomString(int len)
{
int num;
int tem;
Random random = new Random();
string rtuStr = "";
for (int i = 0; i < len; i++)
{
num = random.Next();
/*
* 这里可以选择生成字符和数字组合的验证码
*/
tem = num % 10 + '0';//生成数字
//tem = num % 26 + 'A';//生成字符
rtuStr += Convert.ToChar(tem).ToString();
}
return rtuStr;
}
/// <summary>
/// 生成验证码图片
/// </summary>
/// <param name="randomString">随机字符串</param>
/// <param name="context">Http上下文</param>
private void GenerateVerificationCodeImage(string randomString, HttpContext context)
{
//string str = "OO00"; //前两个为字母O,后两个为数字0
int width = Convert.ToInt32(randomString.Length * 12); //计算图像宽度
Bitmap img = new Bitmap(width, 23);
Graphics gfc = Graphics.FromImage(img); //产生Graphics对象,进行画图
gfc.Clear(Color.White);
DrawLine(gfc, img);
//写验证码,需要定义Font
Font font = new Font("arial", 12, FontStyle.Bold);
System.Drawing.Drawing2D.LinearGradientBrush brush =
new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, img.Width, img.Height), Color.DarkOrchid, Color.Blue, 1.5f, true);
gfc.DrawString(randomString, font, brush, 3, 2);
DrawPoint(img);
gfc.DrawRectangle(new Pen(Color.DarkBlue), 0, 0, img.Width - 1, img.Height - 1);
//将图像添加到页面
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
//更改Http头
context.Response.ClearContent();
context.Response.ContentType = "image/gif";
context.Response.BinaryWrite(ms.ToArray());
//Dispose
gfc.Dispose();
img.Dispose();
context.Response.End();
}
/// <summary>
/// 为生成的验证码图片增加线条
/// </summary>
/// <param name="gfc">Graphics</param>
/// <param name="img">初步生成的验证码图片</param>
private void DrawLine(Graphics gfc, Bitmap img)
{
Random random = new Random();
//选择画10条线,也可以增加,也可以不要线,只要随机杂点即可
for (int i = 0; i < 10; i++)
{
int x1 = random.Next(img.Width);
int y1 = random.Next(img.Height);
int x2 = random.Next(img.Width);
int y2 = random.Next(img.Height);
gfc.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); //注意画笔一定要浅颜色,否则验证码看不清楚
}
}
/// <summary>
/// 为生成的验证码增加点
/// </summary>
/// <param name="img">初步生成的验证码图片</param>
private void DrawPoint(Bitmap img)
{
//选择画100个点,可以根据实际情况改变
Random random = new Random();
for (int i = 0; i < 100; i++)
{
int x = random.Next(img.Width);
int y = random.Next(img.Height);
img.SetPixel(x, y, Color.FromArgb(random.Next()));//杂点颜色随机
}
int col = random.Next();//在一次的图片中杂店颜色相同
for (int i = 0; i < 100; i++)
{
int x = random.Next(img.Width);
int y = random.Next(img.Height);
img.SetPixel(x, y, Color.FromArgb(col));
}
}
}
} --------------------编程问答-------------------- 确实都差不多的 再说网上到处有下的 都有源码的 下个看看就明白了 --------------------编程问答-------------------- 学习 --------------------编程问答-------------------- ding... --------------------编程问答-------------------- MARK --------------------编程问答-------------------- 关注
蹭分 --------------------编程问答-------------------- 好多种,上面给出的只是一般常用的验证码算法。
--------------------编程问答-------------------- ding... --------------------编程问答-------------------- 关注中…… --------------------编程问答-------------------- 三楼的比我现在用的好 --------------------编程问答-------------------- mark --------------------编程问答-------------------- ding --------------------编程问答--------------------
--------------------编程问答-------------------- 收藏了 --------------------编程问答-------------------- ding... --------------------编程问答-------------------- ding... --------------------编程问答-------------------- ding... --------------------编程问答-------------------- ding... --------------------编程问答-------------------- 顶 --------------------编程问答-------------------- ding... --------------------编程问答-------------------- mark.... --------------------编程问答-------------------- --------------------编程问答-------------------- ding... --------------------编程问答-------------------- 做个记号 --------------------编程问答-------------------- ding... --------------------编程问答--------------------
using System;
using System.IO;
using System.Web;
using System.Drawing;
namespace Kissogram.Common.Security
{
//GIF验证码类
public class Validate
{
//设置最少4位验证码
private byte TrueValidateCodeCount = 4;
public byte ValidateCodeCount
{
get
{
return TrueValidateCodeCount;
}
set
{
//验证码至少为3位
if (value > 4)
TrueValidateCodeCount = value;
}
}
protected string ValidateCode = "";
//是否消除锯齿
public bool FontTextRenderingHint = false;
//验证码字体
public string ValidateCodeFont = "Arial";
//验证码型号(像素)
public float ValidateCodeSize = 13;
public int ImageHeight = 23;
//定义验证码中所有的字符
public string AllChar = "1,2,3,4,5,6,7,8,9,0,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z";
//获得随机四位数
private void CreateValidate()
{
ValidateCode = "";
//将验证码中所有的字符保存在一个字符串数组中
string[] CharArray = AllChar.Split(',');
int Temp = -1;
//生成一个随机对象
Random RandCode = new Random();
//根据验证码的位数循环
for (int i = 0; i < ValidateCodeCount; i++)
{
//主要是防止生成相同的验证码
if (Temp != -1)
{
//加入时间的刻度
RandCode = new Random(i * Temp * ((int)DateTime.Now.Ticks));
}
int t = RandCode.Next(35);
if (Temp == t)
{
//相等的话重新生成
CreateValidate();
}
Temp = t;
ValidateCode += CharArray[Temp];
}
//错误检测,去除超过指定位数的验证码
if (ValidateCode.Length > TrueValidateCodeCount)
ValidateCode = ValidateCode.Remove(TrueValidateCodeCount);
}
//生成一帧的BMP图象
private void CreateImageBmp(out Bitmap ImageFrame)
{
//获得验证码字符
char[] CodeCharArray = ValidateCode.ToCharArray(0, ValidateCodeCount);
//图像的宽度-与验证码的长度成一定比例
int ImageWidth = (int)(TrueValidateCodeCount * ValidateCodeSize * 1.3 + 4);
//创建一个长20,宽iwidth的图像对象
ImageFrame = new Bitmap(ImageWidth, ImageHeight);
//创建一个新绘图对象
Graphics ImageGraphics = Graphics.FromImage(ImageFrame);
//清除背景色,并填充背景色
//Note:Color.Transparent为透明
ImageGraphics.Clear(Color.White);
//绘图用的字体和字号
Font CodeFont = new Font(ValidateCodeFont, ValidateCodeSize, FontStyle.Bold);
//绘图用的刷子大小
Brush ImageBrush = new SolidBrush(Color.Red);
//字体高度计算
int FontHeight = (int)Math.Max(ImageHeight - ValidateCodeSize - 3, 2);
//创建随机对象
Random rand = new Random();
//开始随机安排字符的位置,并画到图像里
for (int i = 0; i < TrueValidateCodeCount; i++)
{
//生成随机点,决定字符串的开始输出范围
int[] FontCoordinate = new int[2];
FontCoordinate[0] = (int)(i * ValidateCodeSize + rand.Next(1)) + 3;
FontCoordinate[1] = rand.Next(FontHeight);
Point FontDrawPoint = new Point(FontCoordinate[0], FontCoordinate[1]);
//消除锯齿操作
if (FontTextRenderingHint)
ImageGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
else
ImageGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
//格式化刷子属性-用指定的刷子、颜色等在指定的范围内画图
ImageGraphics.DrawString(CodeCharArray[i].ToString(), CodeFont, ImageBrush, FontDrawPoint);
}
ImageGraphics.Dispose();
}
//处理生成的BMP
private void DisposeImageBmp(ref Bitmap ImageFrame)
{
//创建绘图对象
Graphics ImageGraphics = Graphics.FromImage(ImageFrame);
//创建铅笔对象
Pen ImagePen = new Pen(Color.Red, 1);
//创建随机对象
Random rand = new Random();
//创建随机点
Point[] RandPoint = new Point[2];
//随机画线
for (int i = 0; i < 15; i++)
{
RandPoint[0] = new Point(rand.Next(ImageFrame.Width), rand.Next(ImageFrame.Height));
RandPoint[1] = new Point(rand.Next(ImageFrame.Width), rand.Next(ImageFrame.Height));
ImageGraphics.DrawLine(ImagePen, RandPoint[0], RandPoint[1]);
}
ImageGraphics.Dispose();
}
//创建GIF动画
private void CreateImageGif()
{
Bitmap ImageFrame;
Kissogram.Drawing.Gif.AnimatedGifEncoder GifPic = new Kissogram.Drawing.Gif.AnimatedGifEncoder();
MemoryStream BmpMemory = new MemoryStream();
GifPic.Start();
//确保视觉残留
GifPic.SetDelay(5);
//-1:no repeat,0:always repeat
GifPic.SetRepeat(0);
for (int i = 0; i < 20; i++)
{
//创建一帧的图像
CreateImageBmp(out ImageFrame);
//生成随机线条
DisposeImageBmp(ref ImageFrame);
//输出绘图,将图像保存到指定的流
ImageFrame.Save(BmpMemory, System.Drawing.Imaging.ImageFormat.Png);
GifPic.AddFrame(Image.FromStream(BmpMemory));
BmpMemory = new MemoryStream();
}
GifPic.OutPut(ref BmpMemory);
HttpContext.Current.Response.ClearContent();
//配置输出类型
HttpContext.Current.Response.ContentType = "image/Gif";
//输出内容
HttpContext.Current.Response.BinaryWrite(BmpMemory.ToArray());
BmpMemory.Close();
BmpMemory.Dispose();
}
//输出验证码
public void OutPutValidate(string ValidateCodeSession)
{
CreateValidate();
CreateImageGif();
//把生成的验证码输入到SESSION
HttpContext.Current.Session[ValidateCodeSession] = ValidateCode;
}
}
}
/*这些代码是我在网上找到的,当时也没怎么在意。
后来,我发现这个东西很吊啊!动态跳跃的验证码.
给看个实例吧:
这段源码标示是红色的是另外一个用于把单个图片封装成连续的GIF动画图片的类,所以直接有这些源码是不能创建出来的。
*/
--------------------编程问答-------------------- ding... --------------------编程问答-------------------- 感觉看到很多马甲出现 :)
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.Drawing;
public partial class CheckCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CreateCheckCodeImage(GenerateCheckCode());
}
private string GenerateCheckCode()
{
int number;
char code;
string checkCode = String.Empty;
System.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.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);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
}
我来帮你顶下吧..
验证码基本上都差不多.. --------------------编程问答-------------------- 谢谢楼上各位朋友的回复,
明天就可以补加100分啦。。。 --------------------编程问答-------------------- mark --------------------编程问答-------------------- ding..... --------------------编程问答-------------------- 去找找字母粘连,扭曲的算法,那个可靠性高 --------------------编程问答-------------------- 高手啊 呵呵 学习
一般生成验证码算法都是 随机
至于最终的成果就是字体和图片处理方面的了
21L的感觉不错 --------------------编程问答-------------------- 实用简介明了 就行了 不要像Google那样 太复杂 人家很反感的
代码:
using System;--------------------编程问答-------------------- upup --------------------编程问答--------------------
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 VerifyCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//验证码长度(默认6个验证码的长度)
int length = 4;
public int Length
{
get { return length; }
set { length = value; }
}
//验证码字体大小(为了显示扭曲效果,默认20像素,可以自行修改)
int fontSize = 12;
public int FontSize
{
get { return fontSize; }
set { fontSize = value; }
}
//边框补(默认1像素)
int padding = 1;
public int Padding
{
get { return padding; }
set { padding = value; }
}
//是否输出燥点(默认为输出)
bool chaos = true;
public bool Chaos
{
get { return chaos; }
set { chaos = value; }
}
//输出燥点的颜色(默认灰色)
Color chaosColor = Color.LightGray;
public Color ChaosColor
{
get { return chaosColor; }
set { chaosColor = value; }
}
//自定义背景色(默认白色)
Color backgroundColor = Color.White;
public Color BackgroundColor
{
get { return backgroundColor; }
set { backgroundColor = value; }
}
//自定义随机颜色数组
Color[] colors = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
public Color[] Colors
{
get { return colors; }
set { colors = value; }
}
//自定义字体数组
string[] fonts = { "Arial", "Georgia" };
public string[] Fonts
{
get { return fonts; }
set { fonts = value; }
}
//自定义随机码字符串序列(使用逗号分隔)
// string codeSerial = "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 codeSerial = "0,1,2,3,4,5,6,7,8,9";
public string CodeSerial
{
get { return codeSerial; }
set { codeSerial = value; }
}
//生成校验码图片
public Bitmap CreateImageCode(string code)
{
int fSize = FontSize;
int fWidth = fSize + Padding;
int imageWidth = (int)(code.Length * fWidth) + 4 + Padding * 2;
int imageHeight = fSize * 2 + Padding;
System.Drawing.Bitmap image = new System.Drawing.Bitmap(imageWidth, imageHeight);
Graphics g = Graphics.FromImage(image);
g.Clear(BackgroundColor);
Random rand = new Random();
//给背景添加随机生成的燥点
if (this.Chaos)
{
Pen pen = new Pen(ChaosColor, 0);
int c = Length * 15;
for (int i = 0; i < c; i++)
{
int x = rand.Next(image.Width);
int y = rand.Next(image.Height);
g.DrawRectangle(pen, x, y, 1, 1);
}
}
int left = 0, top = 0, top1 = 1, top2 = 1;
int n1 = (imageHeight - FontSize - Padding * 2);
int n2 = n1 / 4;
top1 = n2;
top2 = n2 * 2;
Font f;
Brush b;
int cindex, findex;
//随机字体和颜色的验证码字符
for (int i = 0; i < code.Length; i++)
{
cindex = rand.Next(Colors.Length - 1);
findex = rand.Next(Fonts.Length - 1);
f = new System.Drawing.Font(Fonts[findex], fSize, System.Drawing.FontStyle.Bold);
b = new System.Drawing.SolidBrush(Colors[cindex]);
if (i % 2 == 1)
{
top = top2;
}
else
{
top = top1;
}
left = i * fWidth;
g.DrawString(code.Substring(i, 1), f, b, left, top);
}
//画一个边框 边框颜色为Color.White
g.DrawRectangle(new Pen(Color.White, 0), 0, 0, image.Width - 1, image.Height - 1);
g.Dispose();
return image;
}
//将创建好的图片输出到页面
public void CreateImageOnPage(string code, HttpContext context)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
Bitmap image = this.CreateImageCode(code);
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
context.Response.ClearContent();
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(ms.GetBuffer());
ms.Close();
ms = null;
image.Dispose();
image = null;
}
//生成随机字符码
public string CreateVerifyCode(int codeLen)
{
if (codeLen == 0)
{
codeLen = Length;
}
string[] arr = CodeSerial.Split(',');
string code = "";
int randValue = -1;
Random rand = new Random(unchecked((int)DateTime.Now.Ticks));
for (int i = 0; i < codeLen; i++)
{
randValue = rand.Next(0, arr.Length - 1);
code += arr[randValue];
}
return code;
}
public string CreateVerifyCode()
{
return CreateVerifyCode(0);
}
}
? --------------------编程问答-------------------- 路过~ --------------------编程问答-------------------- 学习 --------------------编程问答-------------------- xuexi --------------------编程问答-------------------- up --------------------编程问答-------------------- 学习 顶一下 --------------------编程问答-------------------- ding --------------------编程问答-------------------- --------------------编程问答--------------------
public class VerificationCode : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//生成随机的字符串
string randomString = GetRandomString(4);
//将生成的字符串保存到数据库中
BoBoContext.Current.Session["Verification_Code"] = randomString;
//生成验证码图片
GenerateVerificationCodeImage(randomString, context);
}
public bool IsReusable
{
get
{
return false;
}
}
/// <summary>
/// 得到随机字符串,长度自己定义
/// </summary>
/// <param name="len">长度 </param>
/// <returns>指定长度的随机字符串 </returns>
private string GetRandomString(int len)
{
int num;
int tem;
Random random = new Random();
string rtuStr = "";
for (int i = 0; i < len; i++)
{
num = random.Next();
/*
* 这里可以选择生成字符和数字组合的验证码
*/
tem = num % 10 + '0';//生成数字
//tem = num % 26 + 'A';//生成字符
rtuStr += Convert.ToChar(tem).ToString();
}
return rtuStr;
}
/// <summary>
/// 生成验证码图片
/// </summary>
/// <param name="randomString">随机字符串 </param>
/// <param name="context">Http上下文 </param>
private void GenerateVerificationCodeImage(string randomString, HttpContext context)
{
//string str = "OO00"; //前两个为字母O,后两个为数字0
int width = Convert.ToInt32(randomString.Length * 12); //计算图像宽度
Bitmap img = new Bitmap(width, 23);
Graphics gfc = Graphics.FromImage(img); //产生Graphics对象,进行画图
gfc.Clear(Color.White);
DrawLine(gfc, img);
//写验证码,需要定义Font
Font font = new Font("arial", 12, FontStyle.Bold);
System.Drawing.Drawing2D.LinearGradientBrush brush =
new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, img.Width, img.Height), Color.DarkOrchid, Color.Blue, 1.5f, true);
gfc.DrawString(randomString, font, brush, 3, 2);
DrawPoint(img);
gfc.DrawRectangle(new Pen(Color.DarkBlue), 0, 0, img.Width - 1, img.Height - 1);
//将图像添加到页面
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
//更改Http头
context.Response.ClearContent();
context.Response.ContentType = "image/gif";
context.Response.BinaryWrite(ms.ToArray());
//Dispose
gfc.Dispose();
img.Dispose();
context.Response.End();
}
/// <summary>
/// 为生成的验证码图片增加线条
/// </summary>
/// <param name="gfc">Graphics </param>
/// <param name="img">初步生成的验证码图片 </param>
private void DrawLine(Graphics gfc, Bitmap img)
{
Random random = new Random();
//选择画10条线,也可以增加,也可以不要线,只要随机杂点即可
for (int i = 0; i < 10; i++)
{
int x1 = random.Next(img.Width);
int y1 = random.Next(img.Height);
int x2 = random.Next(img.Width);
int y2 = random.Next(img.Height);
gfc.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); //注意画笔一定要浅颜色,否则验证码看不清楚
}
}
/// <summary>
/// 为生成的验证码增加点
/// </summary>
/// <param name="img">初步生成的验证码图片 </param>
private void DrawPoint(Bitmap img)
{
//选择画100个点,可以根据实际情况改变
Random random = new Random();
for (int i = 0; i < 100; i++)
{
int x = random.Next(img.Width);
int y = random.Next(img.Height);
img.SetPixel(x, y, Color.FromArgb(random.Next()));//杂点颜色随机
}
int col = random.Next();//在一次的图片中杂店颜色相同
for (int i = 0; i < 100; i++)
{
int x = random.Next(img.Width);
int y = random.Next(img.Height);
img.SetPixel(x, y, Color.FromArgb(col));
}
}
}
}
都差不多啊 --------------------编程问答-------------------- 新建CheckCode.aspx
using System;
using System.Drawing;
public partial class ValidateCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.CreateCheckCodeImage(GenerateCheckCode());
}
private string GenerateCheckCode()
{
int number;
char code;
string checkCode = String.Empty;
System.Random random = new Random();
for (int i = 0; i < 6; i++)
{
number = random.Next();
if (number % 2 == 0)
code = (char)('0' + (char)(number % 10));
else
code = (char)('A' + (char)(number % 26));
checkCode += code.ToString();
}
Session["CheckCode"] = checkCode;
//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 < 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);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
}
使用,*.aspx内
<asp:Image ID="imgCheckCode" runat="server" ImageUrl="~/CheckCode.aspx" />
--------------------编程问答-------------------- 方法有多种,就看复杂度了,比较全的如3楼所说。
1.清晰的简洁的验证码、用户比较喜欢,但安全系数不高,容易破解,比如只含有4个数字或字母的。
2.复杂的多样的验证码、用户觉得反感因为输入很麻烦,但安全性较高,比如除了多位数字或字母外、还有晦涩的背景、线条、噪音点等等。
总结,根据真正需求选择不同样式的验证码,比如用户量不大,公司内部使用的系统基本上可以选择第一种方案;如果系统是长期挂在公网上、用户量很大、涉及隐私或金钱等,建议使用第二种方案。 --------------------编程问答-------------------- 学习 --------------------编程问答-------------------- using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
/**///// <summary>
/// 页面验证码程序
/// 使用:在页面中加入HTML代码 <img src="VerifyCode.aspx">
/// </summary>
public partial class VerifyCode : System.Web.UI.Page
...{
static string[] FontItems = new string[] ...{ "Arial",
"Helvetica",
"Geneva",
"sans-serif",
"Verdana"
};
static Brush[] BrushItems = new Brush[] ...{ Brushes.OliveDrab,
Brushes.ForestGreen,
Brushes.DarkCyan,
Brushes.LightSlateGray,
Brushes.RoyalBlue,
Brushes.SlateBlue,
Brushes.DarkViolet,
Brushes.MediumVioletRed,
Brushes.IndianRed,
Brushes.Firebrick,
Brushes.Chocolate,
Brushes.Peru,
Brushes.Goldenrod
};
static string[] BrushName = new string[] ...{ "OliveDrab",
"ForestGreen",
"DarkCyan",
"LightSlateGray",
"RoyalBlue",
"SlateBlue",
"DarkViolet",
"MediumVioletRed",
"IndianRed",
"Firebrick",
"Chocolate",
"Peru",
"Goldenrod"
};
private static Color BackColor = Color.White;
private static Pen BorderColor = Pens.DarkGray;
private static int Width = 52;
private static int Height = 21;
private Random _random;
private string _code;
private int _brushNameIndex;
override protected void OnInit(EventArgs e)
...{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
//InitializeComponent();
//base.OnInit(e);
}
/**//**//**//// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
...{
//this.Load += new System.EventHandler(this.Page_Load);
}
/**//// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void Page_Load(object sender, System.EventArgs e)
...{
if (!IsPostBack)
...{
//
// TODO : initialize
//
this._random = new Random();
this._code = GetRandomCode();
//
// TODO : use Session["code"] save the VerifyCode
//
Session["code"] = this._code;
//
// TODO : output Image
//
this.SetPageNoCache();
this.OnPaint();
}
}
/**//**//**//// <summary>
/// 设置页面不被缓存
/// </summary>
private void SetPageNoCache()
...{
Response.Buffer = true;
Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
Response.Expires = 0;
Response.CacheControl = "no-cache";
Response.AppendHeader("Pragma","No-Cache");
}
/**//**//**//// <summary>
/// 取得一个 4 位的随机码
/// </summary>
/// <returns></returns>
private string GetRandomCode()
...{
return Guid.NewGuid().ToString().Substring(0, 4);
}
/**//**//**//// <summary>
/// 随机取一个字体
/// </summary>
/// <returns></returns>
private Font GetFont()
...{
int fontIndex = _random.Next(0, FontItems.Length);
FontStyle fontStyle = GetFontStyle(_random.Next(0, 2));
return new Font(FontItems[fontIndex], 12, fontStyle);
}
/**//**//**//// <summary>
/// 取一个字体的样式
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
private FontStyle GetFontStyle(int index)
...{
switch (index)
...{
case 0:
return FontStyle.Bold;
case 1:
return FontStyle.Italic;
default:
return FontStyle.Regular;
}
}
/**//**//**//// <summary>
/// 随机取一个笔刷
/// </summary>
/// <returns></returns>
private Brush GetBrush()
...{
int brushIndex = _random.Next(0, BrushItems.Length);
_brushNameIndex = brushIndex;
return BrushItems[brushIndex];
}
/**//**//**//// <summary>
/// 绘画事件
/// </summary>
private void OnPaint()
...{
Bitmap objBitmap = null;
Graphics g = null;
try
...{
objBitmap = new Bitmap(Width, Height);
g = Graphics.FromImage(objBitmap);
Paint_Background(g);
Paint_Text(g);
Paint_TextStain(objBitmap);
Paint_Border(g);
objBitmap.Save(Response.OutputStream, ImageFormat.Gif);
Response.ContentType = "image/gif";
}
catch ...{}
finally
...{
if (null != objBitmap)
objBitmap.Dispose();
if (null != g)
g.Dispose();
}
}
/**//**//**//// <summary>
/// 绘画背景颜色
/// </summary>
/// <param name="g"></param>
private void Paint_Background(Graphics g)
...{
g.Clear(BackColor);
}
/**//**//**//// <summary>
/// 绘画边框
/// </summary>
/// <param name="g"></param>
private void Paint_Border(Graphics g)
...{
g.DrawRectangle(BorderColor, 0, 0, Width - 1, Height - 1);
}
/**//**//**//// <summary>
/// 绘画文字
/// </summary>
/// <param name="g"></param>
private void Paint_Text(Graphics g)
...{
g.DrawString(_code, GetFont(), GetBrush(), 3, 1);
}
/**//**//**//// <summary>
/// 绘画文字噪音点
/// </summary>
/// <param name="g"></param>
private void Paint_TextStain(Bitmap b)
...{
for (int n=0; n<30; n++)
...{
int x = _random.Next(Width);
int y = _random.Next(Height);
b.SetPixel(x, y, Color.FromName(BrushName[_brushNameIndex]));
}
}
}
2 页面引用:
<asp:Image ID="getcode" src="VerifyCode.aspx" runat="server" />
一般需要同时提供刷新功能(看不清楚换一张),代码如下
<asp:Image ID="getcode" src="VerifyCode.aspx" runat="server" /> <A href="javascript:getimgcode()">刷新验证码</A>
如使用了母版页,则用如下代码:
<img ID="getcode" alt="" src="VerifyCode.aspx" /> <%--<asp:Image ID="getcode" src="VerifyCode.aspx" runat="server" />--%>
<A href="javascript:getimgcode()">刷新验证码</A> --------------------编程问答-------------------- 学习 --------------------编程问答-------------------- 呵 --------------------编程问答-------------------- ding..... --------------------编程问答-------------------- --------------------编程问答-------------------- ding...... --------------------编程问答-------------------- ding...... --------------------编程问答-------------------- 还记得第一次见朋友用一个函数生成验证码的时候,太震惊了,感觉太不可思议了。 --------------------编程问答-------------------- 学习 --------------------编程问答-------------------- MARK
--------------------编程问答-------------------- ding... --------------------编程问答-------------------- there is so much code, do you fint satisfactory answer?
mark.
--------------------编程问答-------------------- 谢谢楼上各位朋友的回复。。。 --------------------编程问答-------------------- 谢谢楼上各位朋友的回复。。。 --------------------编程问答-------------------- 最近面试刚被问过这个问题.. --------------------编程问答-------------------- 原创作品:
http://blog.csdn.net/aimeast/archive/2010/02/11/5306074.aspx
--------------------编程问答-------------------- 谢谢楼上各位朋友的回复。。。 --------------------编程问答-------------------- 不是我怀疑你啊,你拿不出200分的。。。 --------------------编程问答-------------------- --------------------编程问答-------------------- mark] --------------------编程问答-------------------- 强人好多,OpenCv应该有帮助 --------------------编程问答-------------------- 先标记一下,有空再学习! --------------------编程问答-------------------- 关注,学习中 --------------------编程问答--------------------
随机选取 再加点干扰线 --------------------编程问答-------------------- MARK以后用得上 --------------------编程问答--------------------
--------------------编程问答-------------------- mark --------------------编程问答-------------------- 很多。 --------------------编程问答-------------------- 来看看的,多几个积分啊 --------------------编程问答-------------------- 的确多. --------------------编程问答-------------------- 顶一个。。。。 --------------------编程问答-------------------- 帮忙顶贴了 --------------------编程问答--------------------
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.Drawing;
public partial class common_CheckCode : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
this.CreateCheckCodeImage(GenerateCheckCode());
}
private string GenerateCheckCode()
{
int number;
char code;
string checkCode = String.Empty;
System.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();
}
Session["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)), 20);
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);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
}
就是这个原理 --------------------编程问答-------------------- MARK! --------------------编程问答-------------------- 人生- CSDN社区 ... --------------------编程问答-------------------- 学习了!!! --------------------编程问答-------------------- up
up --------------------编程问答-------------------- very nice --------------------编程问答-------------------- 我根本看不懂 --------------------编程问答-------------------- 20L已经被我收藏,感谢之 --------------------编程问答-------------------- 这么多高手都浮出水面了。。。 --------------------编程问答-------------------- up............. --------------------编程问答-------------------- mark --------------------编程问答-------------------- 好贴要顶! --------------------编程问答-------------------- 学习+mark
--------------------编程问答-------------------- 好帖。。顶,那是必须地
补充:.NET技术 , C#