1.生成随机图片验证码

1.1 页面调用createvalidatecode 生成随机图片验证码方法;

<div class="inputLine">
<label>
验证码</label> <input type="text" maxlength="4" autocomplete="off" name="verifycode" style="ime-mode: disabled;width:40px;"
id="verifycode" class="reg_in_text" ><img onclick="refreshVerify()" alt="点击刷新" id="CheckCode" src="/home/createvalidatecode">
看不清?<a href="javascript:refreshVerify()">换一张</a>
</div>

1.2 HomeController。createvalidatecode 实现方法;

//生成图片验证码并返回一个结果
public ValidateCodeGenerator CreateValidateCode()
{
var num = 0;
string randomText = SelectRandomNumber(5, out num);
Session["ValidateCode"] = num;
ValidateCodeGenerator vlimg = new ValidateCodeGenerator()
{
BackGroundColor = Color.FromKnownColor(KnownColor.LightGray),
RandomWord = randomText,
ImageHeight = 25,
ImageWidth = 100,
fontSize = 14,
};
return vlimg;
}

1.2.1 createvalidatecode 生成图片验证码类:

public class ValidateCodeGenerator : ActionResult
{
/// <summary>
/// 背景颜色
/// </summary>
public Color BackGroundColor { get; set; }
/// <summary>
/// 随机字符
/// </summary>
public string RandomWord { get; set; }
/// <summary>
/// 图片宽度
/// </summary>
public int ImageWidth { get; set; }
/// <summary>
/// 图片高度
/// </summary>
public int ImageHeight { get; set; }
/// <summary>
/// 字体大小
/// </summary>
public int fontSize { get; set; }

public override void ExecuteResult(ControllerContext context)
{
OnPaint(context);
}

static string[] FontItems = new string[] { "tahoma", "Verdana", "Consolas", "Times New Roman" };
static Brush[] BrushItems = new Brush[] { Brushes.OliveDrab, Brushes.ForestGreen, Brushes.DarkCyan, Brushes.LightSlateGray, Brushes.RoyalBlue, Brushes.SlateBlue, Brushes.DarkViolet, Brushes.MediumVioletRed, Brushes.IndianRed, Brushes.Firebrick, Brushes.Chocolate, Brushes.Peru };
static Color[] ColorItems = new Color[] { Color.Green, Color.Blue, Color.Gray, Color.Red, Color.Black, Color.Orange, Color.OrangeRed, Color.Silver };
private int _brushNameIndex;

Random _random = new Random(DateTime.Now.GetHashCode());

/// <summary>
/// 取一个随机字体
/// </summary>
/// <returns></returns>
private Font GetFont()
{
int fontIndex = _random.Next(0, FontItems.Length);
return new Font(FontItems[fontIndex], fontSize, GetFontStyle());
}

/// <summary>
/// 取一个随机字体样式
/// </summary>
/// <returns></returns>
private FontStyle GetFontStyle()
{
switch (DateTime.Now.Second % 2)
{
case 0:
return FontStyle.Regular | FontStyle.Bold;
case 1:
return FontStyle.Italic | FontStyle.Bold;
default:
return FontStyle.Regular | FontStyle.Bold | FontStyle.Strikeout;
}
}

/// <summary>
/// 取一个随机笔刷
/// </summary>
/// <returns></returns>
private Brush GetBrush()
{
_brushNameIndex = _random.Next(0, BrushItems.Length);
return BrushItems[_brushNameIndex];
}

/// <summary>
/// 获取随机颜色
/// </summary>
/// <returns></returns>
private Color GetColor()
{
int colorIndex = _random.Next(0, ColorItems.Length);
return ColorItems[colorIndex];
}

/// <summary>
/// 绘画背景色
/// </summary>
/// <param name="g"></param>
private void Paint_Background(Graphics g)
{
g.Clear(BackGroundColor);
}

/// <summary>
/// 绘画边框
/// </summary>
/// <param name="g"></param>
private void Paint_Border(Graphics g)
{
g.DrawRectangle(Pens.DarkGray, 0, 0, ImageWidth - 1, ImageHeight - 1);
}

/// <summary>
/// 绘画文字
/// </summary>
/// <param name="g"></param>
private void Paint_Text(Graphics g, string text)
{
int x = 1, y = 1;
Brush brush = GetBrush();
for (int i = 0; i < text.Length; i++)
{
x = ImageWidth / text.Length * i - 2;
y = _random.Next(0, 5);
g.DrawString(text.Substring(i, 1), GetFont(), brush, x, y);
}

}

/// <summary>
/// 绘画噪音点
/// </summary>
/// <param name="b"></param>
private void Paint_Stain(Bitmap b)
{
for (int n = 0; n < (ImageWidth * ImageHeight / 40); n++)
{
int x = _random.Next(0, ImageWidth);
int y = _random.Next(0, ImageHeight);
b.SetPixel(x, y, GetColor());
}
}

/// <summary>
/// 画笔事件
/// </summary>
/// <param name="context"></param>
private void OnPaint(ControllerContext context)
{
Bitmap oBitmap = null;
Graphics g = null;

try
{
oBitmap = new Bitmap(ImageWidth, ImageHeight);
g = Graphics.FromImage(oBitmap);

Paint_Background(g);
Paint_Text(g, RandomWord);
Paint_Stain(oBitmap);
//Paint_Border(g);

context.HttpContext.Response.ContentType = "image/gif";
oBitmap.Save(context.HttpContext.Response.OutputStream, ImageFormat.Gif);
g.Dispose();
oBitmap.Dispose();
}
catch
{
context.HttpContext.Response.Clear();
context.HttpContext.Response.Write("Err!");
context.HttpContext.Response.End();
}
finally
{
if (null != oBitmap)
oBitmap.Dispose();
if (null != g)
g.Dispose();
}
}

}

2 图片,文件的上传

public class UpLoadController : BaseController
{
[HttpPost]
public ContentResult UpLoadImage()
{
try
{
var file = Request.Files["imgFile"];
string nameImg = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string resourceSiteUrl = ConfigurationManager.AppSettings["ResourceSiteUrl"].ToString();
string resourceSitePostUrl = ConfigurationManager.AppSettings["ResourceSitePostUrl"].ToString();
string upLoadFile = ConfigurationManager.AppSettings["UpLoadFile"].ToString();
string upLoadPostPath = ConfigurationManager.AppSettings["UpLoadPostPath"].ToString();
nameImg += file.FileName.Substring(file.FileName.LastIndexOf(".")).ToLower();
string url = string.Format("{0}{1}{2}", resourceSiteUrl, upLoadFile, nameImg);

upLoadFile = "/" + ConfigurationManager.AppSettings["WebSiteEName"].ToString() + upLoadFile;

string postUrl = string.Format("{0}{1}?filename={2}&upLoadFile={3}", resourceSitePostUrl, upLoadPostPath, nameImg, upLoadFile);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
request.Method = "POST";
request.AllowAutoRedirect = false;
request.ContentType = "multipart/form-data";
byte[] bytes = new byte[file.InputStream.Length];
file.InputStream.Read(bytes, 0, (int)file.InputStream.Length);
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
HttpWebResponse respon = (HttpWebResponse)request.GetResponse();
Hashtable hash = new Hashtable();
hash["error"] = 0;
hash["url"] = url;
return Content(System.Web.Helpers.Json.Encode(hash), "text/html; charset=UTF-8");

}
catch (Exception ex)
{
var writer = Common.Log.LogWriterGetter.GetLogWriter();
writer.Write("UploadFiles", "-Admin_Upload", ex);
throw ex;
}
}

public string UpLoadFile(string fromFilePath, string toFilePath, string fileName)
{
fromFilePath = "/Xml/test.xml";
toFilePath = "/UpLoad/uploadimages/";
try
{
FileInfo fi = new FileInfo(fromFilePath);
FileStream fs = fi.OpenRead();
string resourceSiteUrl = ConfigurationManager.AppSettings["ResourceSiteUrl"].ToString();

string postUrl = resourceSiteUrl + "/UpLoad/upload_json.aspx" + "?filename=" + fileName + "&upLoadFile=" + toFilePath;

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
request.Method = "POST";
request.AllowAutoRedirect = false;
request.ContentType = "multipart/form-data";
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, (int)fs.Length);

request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
HttpWebResponse respon = (HttpWebResponse)request.GetResponse();
Hashtable hash = new Hashtable();
hash["error"] = 0;
hash["url"] = toFilePath + fileName;

//return Content(System.Web.Helpers.Json.Encode(hash), "text/html; charset=UTF-8");
return "";

}
catch (Exception ex)
{
throw ex;
}
}

}

3.解析html

//采集期号,比赛,结果

var maxIssuseCount = 2;

//取期号
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
long tt = (DateTime.Now.Ticks - startTime.Ticks) / 10000;
var url = "http://trade.500.com/bjdc/index.php";
var encoding = Encoding.GetEncoding("gb2312");
var content = PostManager.Get(url, encoding);

//step 1 得到div内容
var index = content.IndexOf("<option");
content = content.Substring(index);
index = content.IndexOf("</select>");
content = content.Substring(0, index);

var rows = content.Split(new string[] { "</option>" }, StringSplitOptions.RemoveEmptyEntries);

var issuseStrList = new List<string>();
foreach (var item in rows)
{
//var issuse = CutHtml(item).Replace("当前期", "").Replace(" ", "").Replace("第投注比例期","").Replace("第平均赔率期","");
var issuse = CutHtml(item).Replace("当前期", "").Replace(" ", "");
if (string.IsNullOrEmpty(issuse))
continue;
if (issuseStrList.Count >= maxIssuseCount)
break;
issuseStrList.Add(issuse);
}

foreach (var issuseStr in issuseStrList)
{
if (string.IsNullOrEmpty(issuseNumber))
issuseNumber = issuseStr;

var currentIssuseList = new List<KeyValuePair<DBChangeState, BJDC_Issuse>>();
var currentMatchResultList = new List<KeyValuePair<DBChangeState, BJDC_MatchResult>>();
var currentSFGGList = new List<KeyValuePair<DBChangeState, BJDC_Match_SFGG>>();
var currentMatchResult_sfggList = new List<KeyValuePair<DBChangeState, BJDC_Match_SFGGResult>>();
this.WriteLog(string.Format("开始采集期:{0}", issuseStr));

var currentMatchList = BuildLeagueInfoCollectionFrom9188(issuseStr, getResult, out currentIssuseList, out currentMatchResultList, out currentSFGGList, out currentMatchResult_sfggList);
issuseList.AddRange(currentIssuseList);//奖期
leagueList.AddRange(currentMatchList);//比赛
matchResultList.AddRange(currentMatchResultList);//结果
matchsfggList.AddRange(currentSFGGList);
matchResult_sfggList.AddRange(currentMatchResult_sfggList);

this.WriteLog(string.Format("采集到期号{0},赛事队伍条数{1}条", issuseStr, leagueList.Count));
this.WriteLog(string.Format("采集到期号{0},比赛结果{1}条", issuseStr, matchResultList.Count));
this.WriteLog(string.Format("采集到期号{0},胜负过关赛事队伍条数{1}条", issuseStr, matchsfggList.Count));

}

生成随机验证码,上传图片文件,解析HTML的更多相关文章

  1. Python 生成随机验证码

    Python生成随机验证码  Python生成随机验证码,需要使用PIL模块. 安装: 1 pip3 install pillow 基本使用 1. 创建图片 1 2 3 4 5 6 7 8 9 fro ...

  2. Python生成随机验证码

    Python生成随机验证码,需要使用PIL模块. 安装: pip3 install pillow 基本使用 1.创建图片 from PIL import Image img = Image.new(m ...

  3. Django中生成随机验证码(pillow模块的使用)

    Django中生成随机验证码 1.html中a标签的设置 <img src="/get_validcode_img/" alt=""> 2.view ...

  4. Java生成随机验证码

    package com.tg.snail.core.util; import java.awt.Color; import java.awt.Font; import java.awt.Graphic ...

  5. Python使用PIL模块生成随机验证码

    PIL模块的安装 pip3 install pillow 生成随机验证码图片 import random from PIL import Image, ImageDraw, ImageFont fro ...

  6. C#生成随机验证码例子

    C#生成随机验证码例子: 前端: <tr> <td width=" align="center" valign="top"> ...

  7. pillow实例 | 生成随机验证码

    1 PIL(Python Image Library) PIL是Python进行基本图片处理的package,囊括了诸如图片的剪裁.缩放.写入文字等功能.现在,我便以生成随机验证码为例,讲述PIL的基 ...

  8. struts2生成随机验证码图片

    之前想做一个随机验证码的功能,自己也搜索了一下别人写的代码,然后自己重新用struts2实现了一下,现在将我自己实现代码贴出来!大家有什么意见都可以指出来! 首先是生成随机验证码图片的action: ...

  9. .net生成随机验证码图片

    /// <summary> /// 自定义图片验证码函数 /// 该函数将生成一个图片验证码,并将生成的code存放于Session["VerifyCode"]变量内. ...

随机推荐

  1. ServiceStack.Redis简单封装

    首先创建RedisConfig配置类 #region 单例模式 //定义单例实体 private static RedisConfig _redisConfig = null; /// <sum ...

  2. 【C#进阶学习】泛型

    一.泛型引入 需求:传入一个类型(整型/日期/字符串或其他),打印出它的类型和内容. 1.初级版 public class CommonMethod { /// <summary> /// ...

  3. python--线程和进程的初识

    一.进程与线程之间的关系 1.线程是属于进程的,线程运行在进程空间内,同一进程所产生的线程共享同一内存空间,当进程退出时该进程所产生的线程都会被强制退出并清除. 2.线程可与属于同一进程的其它线程共享 ...

  4. Mac下Appnium的Android的UI自动化环境搭建

    1. 安装jdk:略 检查是否安装:执行命令java -version admindeMacBook-Pro-2:~ $ java -version java version "1.8.0_ ...

  5. 初学Mybatis

    首先配置mybatis配置文件 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" &qu ...

  6. vue-cli vue脚手架搭建步骤

    提前在E:\nodejs文件夹下建立node_gobal和node_cache 并配置环境变量NODE_PATH:E:\nodejs\node_global\node_modules 改变用户变量中的 ...

  7. 剑指:包含min函数的栈(min栈)

    题目描述 设计一个支持 push,pop,top 等操作并且可以在 O(1) 时间内检索出最小元素的堆栈. push(x)–将元素x插入栈中 pop()–移除栈顶元素 top()–得到栈顶元素 get ...

  8. Vue2.0 新手入门 — 从环境搭建到发布

    什么是 Vue Vue 是一个前端框架,特点是数据绑定 比如你改变一个输入框 Input 标签的值,会自动同步更新到页面上其他绑定该输入框的组件的值 组件化 页面上小到一个按钮都可以是一个单独的文件. ...

  9. Django 中的缓存问题

    Django 中的缓存问题 简单介绍 ​ 在动态网站中,用户所有的请求,服务器都会去数据库中进行相应的增,删,查,改,渲染模板,执行业务逻辑,最后生成用户看到的页面. ​ 当一个网站的用户访问量很大的 ...

  10. window开机启动

    C:\Users\sunyues\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup 再次文件夹下写脚本就可 @echo off ...