以前一直对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();
}

效果图:

.Net (MVC) 随机生成验证码的更多相关文章

  1. Python随机生成验证码的两种方法

    Python随机生成验证码的方法有很多,今天给大家列举两种,大家也可以在这个基础上进行改造,设计出适合自己的验证码方法方法一:利用range Python随机生成验证码的方法有很多,今天给大家列举两种 ...

  2. Android锁定EditText内容和随机生成验证码

    昨天写了个小Demo,实现了随机生成验证码,和锁定EditText两个小功能,先看一下效果图: 锁定EditText在我们不须要用户编辑EditText内容的时候能够用到,实现还是非常easy的,一行 ...

  3. 随机生成验证码及python中的事务

    1.随机生成验证码 # import random # print(random.random()) #-1的小数 # print(random.randint(,)) #包括1和3 # print( ...

  4. js随机生成验证码以及随机颜色

    Javascript通过Math.random()随机生成验证码. 代码如下: <!DOCTYPE html><html> <head> <meta char ...

  5. 随机生成验证码(JS)

    效果展示 实现原理 1. html:一般就是一个div: <div id="code"></div> ,样式根据需求设计. 2. JS:1)将所有的验证码所 ...

  6. php随机生成验证码代码

    <?php session_start(); //产生一个随机的字符串验证码 $checkcode=""; for ($i=0;$i<4;$i++){ $checkco ...

  7. js随机生成验证码及其颜色

    今天迎来了2018年第一场雪,这个美好的日子,总的写点什么纪念一下,在这里写了一个在js中使用Math.random()函数,随机生成四位数的验证码及其验证码换颜色. js代码如下: var arra ...

  8. Djaingo 随机生成验证码(PIL)

    基础: https://www.cnblogs.com/wupeiqi/articles/5812291.html 实例: https://www.cnblogs.com/6324TV/p/88112 ...

  9. java随机生成验证码

    package com.yuyuchen.util; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; im ...

随机推荐

  1. MenuStrip菜单递归

    C# TreeView菜单,MenuStrip菜单递归动态生成例子 http://www.cnblogs.com/ajiaojiao0303/articles/1884772.html http:// ...

  2. DOM2

    DOM级别 文档类型: 节点类型: 判断节点类型(注意Node对象): <div id="container">这是一个元素节点</div> <scr ...

  3. perl学习笔记(4)——动态加载

    在写perl的时候,如果要应用到各种平台的话,比如linux 和windows,会遇到各种问题,有时就是要根据系统类型来加载各种库,之前写的就是这样的, if($^O eq 'linux'){ use ...

  4. 【转】android出现注: 某些输入文件使用或覆盖了已过时的 API。 注: 有关详细信息, 请使用 -Xlint:deprecation 重新编译。 注: 某些输入文件使用了未经检查或不安全的操作。 注

    使用Android studio打包应用程序出现如下错误: 注: 某些输入文件使用或覆盖了已过时的 API. 注: 有关详细信息, 请使用 -Xlint:deprecation 重新编译. 注: 某些 ...

  5. Object Pascal对象模型中构造函数之研究

    http://www.delphi2007.net/delphiblog/html/delphi_2004511950333715.html 前言 近期,一直在使用 C++ 与 Object Pasc ...

  6. C++学习笔记之迭代器

    模板是的算法独立于存储的数据类型,而迭代器使算法独立于使用的容器类型.理解迭代器是理解STL的关键. 迭代器应该具备的特征: (1)应该能够对迭代器进行解除引用的操作,以便能够访问它引用的值.即如果P ...

  7. javascript实现继承的方式

    this this表示当前对象,如果在全局作用范围内使用this,则指代当前页面对象window: 如果在函数中使用this,则this指代什么是根据运行时此函数在什么对象上被调用. 我们还可以使用a ...

  8. C# 实现对网站数据的采集和抓取

    首先大家需要清楚一点的是:任何网站的页面,无论是php.jsp.aspx这些动态页面还是用后台程序生成的静态页面都是可以在浏览器中查看其HTML源文件的. 所以当你要开发数据采集程序的时候,你必须先对 ...

  9. [Jobdu] 题目1527:首尾相连数组的最大子数组和

    题目描述: 给定一个由N个整数元素组成的数组arr,数组中有正数也有负数,这个数组不是一般的数组,其首尾是相连的.数组中一个或多个连续元素可以组成一个子数组,其中存在这样的子数组arr[i],…arr ...

  10. C#程序通过模板自动创建Word文档

    引言:前段时间有项目要用c#生成Word格式的计算报告,通过网络查找到很多内容,但是都很凌乱,于是自己决定将具体的步骤总结整理出来,以便于更好的交流和以后相似问题可以迅速的解决! 现通过具体的示例演示 ...