以前一直对C#的GDI画图部分知识点不怎么用所以忘得差不多了,这两天正好公司要做一个博客系统,其中一个需求就是留言时为了防止恶意攻击必须填写验证码,正好借着这个机会复习了一下,以下是实现代码,写的比较简单。
View 层
@{
ViewBag.Title = "Home Page";
}
<div class="row">
<h1>test</h1>
<div class="col-lg-12">
@using(Html.BeginForm("Index","Home", FormMethod.Post, new {@id="form",@enctype = "multipart/form-data" }))
{
<div class="form-group">
<input type="file" name="file"/>
<input type="file" name="files" />
<button>提交</button>
</div>
<div class="form-group">
<div class="col-lg-1">
<input type="text" class="col-lg-3"/>
</div>
<div class="col-lg-3">
<img id="img" onclick="CheckCode()" src="/Home/GetValidateCode" style="height:30px;width:110px" title="点击更换" alt="点击更换" />
<a href="javascript:void(0)" onclick="CheckCode()">点击更换</a>
</div>
</div>
}
</div>
</div>
@section scripts{
<script>
$(function () {
$("#img").click(function () {
CheckCode()
})
})
function CheckCode() {
$("#img").attr("src", "/Home/GetValidateCode?date="+new Date());
} </script>
}
Controller 层
/// <summary>
/// View页面请求获得验证码
/// </summary>
public void GetValidateCode()
{
//获取随机生成的编码
string ValiDateCode = GetValiDateCode();
Session["Key"] = ValiDateCode;
byte[] bytes = GetValidateCode(ValiDateCode);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(bytes);
// 也可以用MVC 的FileResult
//return File(bytes, @"image/jpeg");
} /// <summary>
/// 生成验证码方法
/// </summary>
/// <param name="ValiDateCode"></param>
/// <returns></returns>
public static byte[] GetValidateCode(string ValiDateCode)
{
Bitmap img = new Bitmap((int)Math.Ceiling(ValiDateCode.Length * 12.6), ); //创建 Bitmap对象
Graphics graphics = Graphics.FromImage(img); //创建 Graphics 对象
graphics.Clear(Color.White); //清空图片背景色
Random random = new Random(); //创建 Random 实例
for (int i = ; i <= ; i++)
{
int x1 = random.Next(img.Width);
int x2 = random.Next(img.Width);
int y1 = random.Next(img.Height);
int y2 = random.Next(img.Height);
graphics.DrawLine(new Pen(Color.Silver),x1, y1, x2, y2); //在图片上画噪点线
}
Font font = new Font("Arial", ,(FontStyle.Bold));
//创建 Brush 对象, LinearGradientBrush实现字体渐变效果 LinearGradientBrush(Rectangle rectangle,Color color1,Color color2,float angle, bool isAngleScaleable)
LinearGradientBrush linear = new LinearGradientBrush(new Rectangle(, , img.Width, img.Height), Color.Gray, Color.Blue, 1.4f, true);
graphics.DrawString(ValiDateCode, font, linear, , ); //绘制生成的验证码,
graphics.DrawRectangle(new Pen(Color.Silver), , , img.Width - , img.Height - );
MemoryStream stream = new MemoryStream(); //创建 流对象
img.Save(stream, ImageFormat.Jpeg); //将图像以特定的格式保存到流对象中
return stream.ToArray();
} /// <summary>
/// 获取随机生成的验证码
/// </summary>
/// <returns></returns>
private static string GetValiDateCode()
{
string[] letter = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "i", "m", "n", "o", "p", "Q" };
Random random = new Random();
StringBuilder result = new StringBuilder();
for (int i = ; i <= ; i++)
{
if (i % == )
{
result.Append(letter[random.Next(, )]);
}
else
{
result.Append(random.Next(, ));
}
}
return result.ToString();
}
效果图: