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控件接受验证码图片
浙公网安备 33010602011771号