直接上代码了

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Manage.Controllers
{
public class ValidateCodeController : Controller
{
//
// GET: /ValidateCode/
public FileContentResult GetCode()
{
//string code = GetRndStr();
string code = GetNumAndStr(4);
byte[] imageByte;
using (Bitmap img = CreateImages(code, "ch"))
{
imageByte = BitmapToByte(img);
Session["validate"] = code;
}
return File(imageByte, "image/gif");
}
public static byte[] BitmapToByte(Bitmap bitmap)
{
using (MemoryStream stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Jpeg);
byte[] data = new byte[stream.Length];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(data, 0, Convert.ToInt32(stream.Length));
return data;
}
}

public bool IsReusable
{
get
{
return false;
}
}
/// <summary>
/// 数字随机数
/// </summary>
/// <returns></returns>
private string GetRndNum()
{
string code = string.Empty;
Random random = new Random();
for (int i = 0; i < 4; i++)
{
code += random.Next(9);
}
return code;
}
/// <summary>
/// 英文随机
/// </summary>
/// <returns></returns>
private string GetRndStr()
{
string Vchar = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] VcArray = Vchar.Split(',');
string checkCode = string.Empty;
Random rand = new Random();
for (int i = 0; i < 4; i++)
{
int t = rand.Next(VcArray.Length);
checkCode += VcArray[t];
}
return checkCode;
}
/// <summary>
/// 中文随机
/// </summary>
/// <returns></returns>
private string GetRndCh()
{
System.Text.Encoding gb = System.Text.Encoding.Default;//获取GB2312编码页(表)
object[] bytes = CreateRegionCode(4);//生4个随机中文汉字编码
string[] str = new string[4];
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < 4; i++)
{
//根据汉字编码的字节数组解码出中文汉字
str[i] = gb.GetString((byte[])Convert.ChangeType(bytes[i], typeof(byte[])));
sb.Append(str[i].ToString());
}
return sb.ToString();
}
/// <summary>
/// 产生随机中文字符
/// </summary>
/// <param name="strlength"></param>
/// <returns></returns>
private static object[] CreateRegionCode(int strlength)
{
//定义一个字符串数组储存汉字编码的组成元素
string[] rBase = new String[16] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
Random rnd = new Random();
object[] bytes = new object[strlength];

for (int i = 0; i < strlength; i++)
{
//区位码第1位
int r1 = rnd.Next(11, 14);
string str_r1 = rBase[r1].Trim();
//区位码第2位
rnd = new Random(r1 * unchecked((int)DateTime.Now.Ticks) + i);
int r2;
if (r1 == 13)
{
r2 = rnd.Next(0, 7);
}
else
{
r2 = rnd.Next(0, 16);
}
string str_r2 = rBase[r2].Trim();

//区位码第3位
rnd = new Random(r2 * unchecked((int)DateTime.Now.Ticks) + i);//更换随机种子
int r3 = rnd.Next(10, 16);
string str_r3 = rBase[r3].Trim();

//区位码第4位
rnd = new Random(r3 * unchecked((int)DateTime.Now.Ticks) + i);
int r4;
if (r3 == 10)
{
r4 = rnd.Next(1, 16);
}
else if (r3 == 15)
{
r4 = rnd.Next(0, 15);
}
else
{
r4 = rnd.Next(0, 16);
}
string str_r4 = rBase[r4].Trim();
//定义两个字节变量存储产生的随机汉字区位码
byte byte1 = Convert.ToByte(str_r1 + str_r2, 16);
byte byte2 = Convert.ToByte(str_r3 + str_r4, 16);

//将两个字节变量存储在字节数组中
byte[] str_r = new byte[] { byte1, byte2 };

//将产生的一个汉字的字节数组放入object数组中
bytes.SetValue(str_r, i);
}
return bytes;
}

public string GetNumAndStr(int length)
{
string str = string.Empty;
string Vchar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p" +
",q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q" +
",R,S,T,U,V,W,X,Y,Z";

string[] VcArray = Vchar.Split(new Char[] { ',' });//拆分成数组
string[] num = new string[length];

int temp = -1;//记录上次随机数值,尽量避避免生产几个一样的随机数

Random rand = new Random();
//采用一个简单的算法以保证生成随机数的不同
for (int i = 1; i < length + 1; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));
}

int t = rand.Next(61);

temp = t;
str += VcArray[t];
// num[i - 1] = VcArray[t];
}
return str;
}
/// <summary>
/// 画图片的背景图+干扰线
/// </summary>
/// <param name="checkCode"></param>
/// <returns></returns>
private Bitmap CreateImages(string checkCode, string type)
{
int step = 0;
if (type == "ch")
{
step = 5;//中文字符,边界值做大
}
int iwidth = (int)(checkCode.Length * (13 + step));
System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 22);
Graphics g = Graphics.FromImage(image);
g.Clear(Color.White);//清除背景色
Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };//定义随机颜色
string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
Random rand = new Random();

for (int i = 0; i < 50; i++)
{
int x1 = rand.Next(image.Width);
int x2 = rand.Next(image.Width);
int y1 = rand.Next(image.Height);
int y2 = rand.Next(image.Height);
g.DrawLine(new Pen(Color.LightGray, 1), x1, y1, x2, y2);//根据坐标画线
}

for (int i = 0; i < checkCode.Length; i++)
{
int cindex = rand.Next(7);
int findex = rand.Next(5);

Font f = new System.Drawing.Font(font[findex], 10, System.Drawing.FontStyle.Bold);
Brush b = new System.Drawing.SolidBrush(c[cindex]);
int ii = 4;
if ((i + 1) % 2 == 0)
{
ii = 2;
}
g.DrawString(checkCode.Substring(i, 1), f, b, 3 + (i * (12 + step)), ii);

}
g.DrawRectangle(new Pen(Color.Silver, 0), 0, 0, image.Width - 1, image.Height - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
return image;
}
}
}

前台页面:

<img id="imgCode" onclick="CodeChange();" style="cursor: pointer; height: 40px; width: 105.3px; margin-bottom:-14px;margin-top:0px; margin-right:0px;" title="看不清?" />

$(function () {
$("#imgCode").attr("src", "/ValidateCode/GetCode?t=" + (new Date()).valueOf());
})

// 更换图片验证码
function CodeChange() {
var imgNode = $("#imgCode");
imgNode.attr("src", "/ValidateCode/GetCode?t=" + (new Date()).valueOf());
}

FileContentResult类型的返回一个图片文件

MVC中登录页图片验证码总结的更多相关文章

  1. MVC伪一个12306图片验证码

    本文的来由主要是满足自己的好奇心,而不是证明什么东西,如果涉及到什么官方性的事情,麻烦通知我谢谢:本篇将要和大家分享的是一个看起来通12306图片验证码相似的效果,这篇应该是今年农历最后一篇分享文章了 ...

  2. .NET MVC中登录过滤器拦截的两种方法

    今天给大家介绍两种ASP中过滤器拦截的两种方法. 一种是EF 的HtppModule,另一种则是灵活很多针对MVC的特性类 Attribute 具体什么是特性类可以参考着篇文章:https://www ...

  3. Spring MVC 中使用 Google kaptcha 验证码

    验证码是抵抗批量操作和恶意登录最有效的方式之一. 验证码从产生到现在已经衍生出了很多分支.方式.google kaptcha 是一个非常实用的验证码生成类库. 通过灵活的配置生成各种样式的验证码,并将 ...

  4. 2-功能1:基于用户认证组件和Ajax实现登录验证(图片验证码)

    1.登录页面的设计 (1)label标签的id属性 label标签的id属性,点击label标记,相当于点击了input框 bootstarp样式 class="form-group&quo ...

  5. python爬虫模拟登录的图片验证码处理和会话维持

    目标网站:古诗文网 登录界面显示: 打开控制台工具,输入账号密码,在ALL栏目中进行抓包 数据如下: 登录请求的url和请求方式 登录所需参数 参数分析: __VIEWSTATE和__VIEWSTAT ...

  6. 如何在MVC中显示条形码图片(以内存流的方式)

    前台代码: <script type="text/javascript"> function fresh() { var getimagecode = document ...

  7. .NET MVC中如何使用手机验证码注册登陆

    #region 手机验证码 /// <summary> /// /// </summary> /// <param name="Yonghushouji&quo ...

  8. MVC 中使用kindEditor 图片上传在IE 上进行上传出现的问题

    在IE 上使用KindEditor 进行单张图片上传的时候会出现一个下载安全警告,这样将会造成图片上传失败,出现的错误页面:

  9. Springboot+SpringSecurity实现图片验证码登录问题

    这个问题,网上找了好多,结果代码都不全,找了好多,要不是就自动注入的类注入不了,编译报错,要不异常捕获不了浪费好多时间,就觉得,框架不熟就不能随便用,全是坑,气死我了,最后改了两天.终于弄好啦; 问题 ...

随机推荐

  1. IOS_FMDB有关字典、数组存储及获取问题

    http://blog.csdn.net/betterbb/article/details/25984455 FMDB存储字典或数组时会变成字符串存入sqlite里,但如果不将其转换成json格式存储 ...

  2. 全方位分析Objcetive-C Runtime 分类: ios技术 2015-03-11 22:29 77人阅读 评论(0) 收藏

    本文详细整理了 Cocoa 的 Runtime 系统的知识,它使得 Objective-C 如虎添翼,具备了灵活的动态特性,使这门古老的语言焕发生机.主要内容如下: 引言 简介 与Runtime交互 ...

  3. Cocos2d-x 的“HelloWorld” 深入分析

    本节所用Cocos2d-x版本:cocos2d-1.0.1-x-0.12.0 不能免俗,一切都从“HelloWorld!”开始.打开HelloWorld工程,里面有两个文件目录Classes和win3 ...

  4. ios-贝塞尔曲线

    git下载地址:git@github.com:lu459700780/UIBezierPath.git 演示: #import "ViewController.h" @interf ...

  5. BZOJ 1455: 罗马游戏 [可并堆]

    1455: 罗马游戏 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 1715  Solved: 718[Submit][Status][Discuss] ...

  6. UVa 11308 - Bankrupt Baker

    题目大意:给出一些原料和价钱和若干份菜谱,每份菜谱都标明所需的原料和数量,找出所有不超过预算的菜谱. 没什么好说的,主要是对map的运用. #include <cstdio> #inclu ...

  7. pypi 的使用

    关于本人的package,情况比较简单,所有的.py文件全部放到了一个叫做FundsData的文件夹下(package下),上层目录也叫FundsData(其实叫什么都可以),其下放了setup.py ...

  8. Android studio的那些bug

    R文件无法编译: 1.Activity继承类AppCompatActivity有时候会报错 2.R文件找不到一般是layout文件夹下出错 3.sdk包问题 4.Gradle DSL method n ...

  9. Bzoj3473

    传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=3473 题解:待更 代码:待更 开始时间: 结束时间:

  10. python with用法

    python中with可以明显改进代码友好度,比如: with open('a.txt') as f: print f.readlines() 为了我们自己的类也可以使用with, 只要给这个类增加两 ...