VCode.cs
protected void Page_Load(object sender, EventArgs e)
{
//调用方法,生成验证码
string code = getNum(5);
Session[EnumConst.VCODE_SESSION] = code;//将验证码保存在Session内置对象中
StringBuilder str = new StringBuilder();
for (int i = 0; i < code.Length; i++)
{
str.Append(code.Substring(i, 1) + " ");
}
createImage(str.ToString());
}
//生成随机数
private string getNum(int stringLength)
{
StringBuilder str = new StringBuilder();
Random ran = new Random();
for (int i = 0; i < stringLength; i++)
{
str.Append(ran.Next(10)); //生成0-9的数字
}
return str.ToString(); //返回字符
}
//获得验证图片
private void createImage(string stringCode)
{
Bitmap image = new Bitmap(stringCode.Length * 12, 30); //设置图片大小
Graphics g = Graphics.FromImage(image); //定义画笔
g.Clear(Color.White); //背景颜色
string[] fonts = { "FZSTK", "VINERITC", "STCAIYUN", "HARNGTON" };
Color[] colors = { Color.Red, Color.Green, Color.Blue};
Random random = new Random();
int x = 10;
for (int i = 0; i < stringCode.Length; i++)
{
string strCode = stringCode.Substring(i, 1);
Font font = new System.Drawing.Font(fonts[random.Next(0, 4)], 16, (System.Drawing.FontStyle.Bold));
g.DrawString(strCode, font, new SolidBrush(colors[random.Next(0, 3)]), x, 5);
x = x + 10;
}
// 画图片的边框线
g.DrawRectangle(new Pen(Color.Blue), 0, 0, image.Width - 1, image.Height - 1);
image.Save(Response.OutputStream, ImageFormat.Gif);//显示到页面
g.Dispose();
image.Dispose();
}
前台
<img id="img_captcha" onclick="changeCaptcha()" title="点击更换验证码" /><span id="sMsg" runat="server" style="color: red; max-width: 100px;"></span>
//更换验证码
function changeCaptcha() {
document.getElementByIdx_x_x("img_captcha").src = 'Resources/VCode.aspx?_r=' + Math.random();
}