• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
零星的记忆
博客园    首页    新随笔    联系   管理    订阅  订阅

asp.net 的验证码

思路:

 1.先取出四个随机数字和字母

 2.绘制图片

 3.将随机数加载到图片上

 4.添加干扰线,干扰点和边框线

代码:

创建一个名为code.aspx的web窗体

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

public partial class code : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//产生随机数
string code = "";
string[] a=new string[]{"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"};

Random rand = new Random();
for (int i = 0; i < 4; i++)
{
int start = rand.Next(a.Length);
code += a[start];
}


Bitmap img = new Bitmap(60, 30);
Graphics g = Graphics.FromImage(img);


SolidBrush brush = new SolidBrush(Color.Pink);
g.FillRectangle(brush, 0, 0, 60, 30);

brush.Color = Color.Blue;

Font font = new Font("宋体", 18);
g.DrawString(code, font, brush, 1, 1);

//加干扰线
// for循环用来生成一些随机的水平线
Pen blackPen = new Pen(Color.White, 0);
Random ran = new Random();
for (int i=0;i<5;i++)
{
int y = rand.Next(img.Height);
g.DrawLine(blackPen,0,y,img.Width,y);
}

//生成干扰点
for (int i = 0; i < 100; i++)
{
int x = rand.Next(img.Width);
int y = rand.Next(img.Height);

img.SetPixel(x, y, Color.FromArgb(rand.Next()));
}
//边框
g.DrawRectangle(new Pen(Color.Silver), 0, 0, img.Width - 1, img.Height - 1);


img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

}
}

 

页面:添加一image控件接受验证码图片

posted @ 2013-05-30 19:42  零星的记忆  阅读(96)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3