ASP.NET 中图像验证码的实现

图像验证码在Web登录界面中很常见,以下是用C#写的一个简单例子。

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(7025);
            
//设置图像背景色
            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 on 2005-05-16 14:09  ~~John 的网络涂鸦纪实~~  阅读(899)  评论(6编辑  收藏  举报

导航