图形验证码的实现【转载】

图像验证码在Web登录界面中很常见,以下是用C#写的一个简单例子。【本文转载自http://www.cnblogs.com/JohnXP/archive/2006/09/29/156383.html#518411

1.首先创建一个 ValidateImage.aspx 页,注意引用System.Drawing和System.Drawing.Imaging两个命名空间。
代码如下:

public class ValidateImage : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
//生成验证码
string validateCode=CreateValidateCode();
//生成图像
            Bitmap bitmap=new Bitmap(70, 25);
//设置图像背景色
            SetBgColor(bitmap,Color.Brown);
// 绘制图像干扰
            DrawDisturb(bitmap);
// 绘制验证码
            DrawValidateCode(bitmap, validateCode);
// 保存验证码图像,等待输出
            bitmap.Save(Response.OutputStream, ImageFormat.Gif);
        }

// 生成 A-Z 的四位验证码
private string CreateValidateCode()
{
string validateCode=string.Empty;
            Random random=new Random();

for(int i=0; i<4; i++)
{
//n=1~26
int n=random.Next(26);
                validateCode+=(char)(n+65);
            }

// 保存验证码
            Session["ValidateCode"]=validateCode;
return validateCode;
        }

private void SetBgColor(Bitmap bitmap,Color color)
{
for(int x=0; x<bitmap.Width; x++)
{
for(int y=0; y<bitmap.Height; y++)
{
                    bitmap.SetPixel(x, y, color);
                }
            }
        }
private void DrawDisturb(Bitmap bitmap)
{
            Random random=new Random();

for(int x=0; x<bitmap.Width; x++)
{
for(int y=0; y<bitmap.Height; y++)
{
// 50? 根据自己需要的干扰浓度进行设置
if(random.Next(100)<=50)
                        bitmap.SetPixel(x, y, Color.White);
                }
            }
        }

private void DrawValidateCode(Bitmap bitmap, string validateCode)
{
// 获取绘制器对象
            Graphics g=Graphics.FromImage(bitmap);

// 设置绘制字体
            Font font=new Font("Arial", 14, FontStyle.Bold | FontStyle.Italic);

//绘制的起始位置
int posX=2;
int posY=2;

// 绘制验证码图像
            g.DrawString(validateCode, font, Brushes.Black, posX, posY);
        }
2.验证码的使用
在需要验证码的网页中,直接使用就可以了。
<img src="ValidateImage.aspx" style="border-color:#000000;border-width:1px;border-style:Solid">
相应的Session可以从Session["ValidateCode"]中取得

posted @ 2008-08-17 12:07  陈希章  阅读(1306)  评论(0编辑  收藏  举报