using System;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.getJpg();
}
//将验证码画在图像上
protected void getJpg()
{
//定义一个长度
int length = 6;
//创建一个图像
Bitmap Bit = new Bitmap(120, 40);
//创建一个绘图图像
Graphics g = Graphics.FromImage(Bit);
//调用getLength()方法来获取图像中显示的验证码
string strcheck = this.getLength(length);
//为图像添加背景色
g.Clear(Color.DarkGreen);
//图像中验证码显示的字体与大小
Font f = new Font("@Batang",20);
//文本的布局,此处为空,默认布局
StringFormat SF = new StringFormat();
//在指定的区域绘制字符串
g.DrawString(strcheck, f, Brushes.Orange, 1f, 1f, SF);
//为背景随机添加横线,为了不让横线重复,取了时间的毫秒部分
Random R = new Random(DateTime.Now.Millisecond);
for (int i = 0; i < 10; i++)
{
int y = R.Next(Bit.Height);
g.DrawLine(new Pen(Color.Black,0), 0, y, Bit.Width, y);
}
//创建一个存取流,需要倒包using System.IO
MemoryStream MS = new MemoryStream();
//将图像以Jpg的格式保存到MS流中
Bit.Save(MS, System.Drawing.Imaging.ImageFormat.Jpeg);
//将二进制字符串写入到Http输出流
this.Response.BinaryWrite(MS.ToArray());
}
//得到验证码的数字
private string getLength(int strlength)
{
//自定义一个字符串
string str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
//定义一个空的字符串,以保存验证码数字
string str1 = "";
//随机生成数字,取时间毫秒部分是为了不让数字重复
Random RD = new Random(DateTime.Now.Millisecond);
for (int i = 0; i < strlength; i++)
{
str1 += str[RD.Next(0,61)];//在0-61之间取数
}
return str1;//返回得到的验证码
}
}
最后结果: