MVC图片验证码

时间:2022-01-29 13:55:50

C#类库:

 public class YZM
{
public string YZMcode = String.Empty; public byte[] load()
{ Bitmap bit = new Bitmap(, );//画布大小
Graphics g = Graphics.FromImage(bit);//创建绘制对象,告诉它往哪张图片上绘制
try { Random r = new Random();
Color color1 = Color.FromArgb(r.Next(, ), r.Next(, ), r.Next(, ));
g.FillRectangle(new SolidBrush(color1), , , , );//画布颜色随机
for (int i = ; i < ; i++)//随机画干扰线
{
Color color3 = Color.FromArgb(r.Next(, ), r.Next(, ), r.Next(, ));
Pen pp = new Pen(new SolidBrush(color3), r.Next(, ));
g.DrawLine(pp, r.Next(, ), r.Next(, ), r.Next(, ), r.Next(, ));
} string yan = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";//设置随机的验证码,从里面抽取
int wei = ;
for (int i = ; i < ; i++)//取四位验证码,颜色随机
{
string m = yan.Substring(r.Next(, yan.Length), );
YZMcode += m;
Color color2 = Color.FromArgb(r.Next(, ), r.Next(, ), r.Next(, ));
int w = r.Next(, );
Font f = new Font("黑体", w);
SolidBrush b = new SolidBrush(color2); g.DrawString(m, f, b, wei, r.Next(, ));
wei += w;
} for (int i = ; i < ; i++)
{
Color color3 = Color.FromArgb(r.Next(, ), r.Next(, ), r.Next(, ));
Pen pp = new Pen(new SolidBrush(color3), r.Next(, ));
int a = r.Next(, );
int b = r.Next(, );
g.DrawLine(pp, a, b, (a + ), (b + ));
} System.IO.MemoryStream ms = new System.IO.MemoryStream();
bit.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
finally {
g.Dispose();//释放绘图对象
bit.Dispose();//释放图像对象
} } }

action:

 public FileContentResult yIndex()
{
YZM y = new YZM();
byte[] bytes = y.load();
Session["yzm"] = y.YZMcode;
return File(bytes, @"image/jpeg");
}

HTML:

<img alt="验证码图片"  id="img" src="@Url.Action("yIndex","Home")" style="width: 100px; height: 38px; border: 1px solid #ddd; margin-bottom: -15px;"  />
<a href="#" onclick="fun()" style="color: #1b66c7">换一张</a>

js:

<script>
var i = 0;
function fun()
{
$("#img")[0].src = $("#img")[0].src + "?" +i;
i++;
}
</script>