生成随机验证码,上传图片文件,解析HTML
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的更多相关文章
- Python 生成随机验证码
Python生成随机验证码 Python生成随机验证码,需要使用PIL模块. 安装: 1 pip3 install pillow 基本使用 1. 创建图片 1 2 3 4 5 6 7 8 9 fro ...
- Python生成随机验证码
Python生成随机验证码,需要使用PIL模块. 安装: pip3 install pillow 基本使用 1.创建图片 from PIL import Image img = Image.new(m ...
- Django中生成随机验证码(pillow模块的使用)
Django中生成随机验证码 1.html中a标签的设置 <img src="/get_validcode_img/" alt=""> 2.view ...
- Java生成随机验证码
package com.tg.snail.core.util; import java.awt.Color; import java.awt.Font; import java.awt.Graphic ...
- Python使用PIL模块生成随机验证码
PIL模块的安装 pip3 install pillow 生成随机验证码图片 import random from PIL import Image, ImageDraw, ImageFont fro ...
- C#生成随机验证码例子
C#生成随机验证码例子: 前端: <tr> <td width=" align="center" valign="top"> ...
- pillow实例 | 生成随机验证码
1 PIL(Python Image Library) PIL是Python进行基本图片处理的package,囊括了诸如图片的剪裁.缩放.写入文字等功能.现在,我便以生成随机验证码为例,讲述PIL的基 ...
- struts2生成随机验证码图片
之前想做一个随机验证码的功能,自己也搜索了一下别人写的代码,然后自己重新用struts2实现了一下,现在将我自己实现代码贴出来!大家有什么意见都可以指出来! 首先是生成随机验证码图片的action: ...
- .net生成随机验证码图片
/// <summary> /// 自定义图片验证码函数 /// 该函数将生成一个图片验证码,并将生成的code存放于Session["VerifyCode"]变量内. ...
随机推荐
- Application类-应用程序生命周期
1.创建Application对象 新建WPF程序后,排除掉WPF自动创建的App.xaml,我们自定义一个类,在该类的Main()方法中,创建Application对象,然后调用创建一个窗口对象,最 ...
- System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false
多线程程序中,新创建的线程不能访问UI线程创建的窗口控件,这时如果想要访问窗口的控件,发现无法对其控制. 这时可将窗口构造函数中的CheckForIllegalCrossThreadCalls设置为f ...
- Jenkins的使用(三)-------Publish over SSH和Publish over FTP
七.构建后操作 1.使用Publish over SSH 1.左边菜单栏 Manage Jenkins --->ManagePlugins--->可选插件,然后搜索 Publish ...
- c#页面重定向,Server.Transfer 和 Response.Redirect
Server.Transfer() 重定向发生在服务器端,把处理的控制权从当前页面转移到另一个页面,在转移的工程中没有离开服务器内部控件(如request,session等)保存的信息不变. 1.只能 ...
- loadrunner 由mdrv进程终止导致的非正常终止
因为脚本迭代次数多的问题,迭代了3次,后来改成了迭代1次(1个Vuser),就不会了,
- WPF布局介绍(1)
开局一张图,内容全靠...,本系列的文章, 主要针对刚入门.亦或是从 winform/bs转过来的开发人员快速入门的指南, 相对于其它一些文章中会详细的从项目如何建立到其实现的原理及组成部分, 本系列 ...
- Linux实用指令(5)
指定运行级别(系统的制定级别配置文件/etc/inittab): 0:关机 1:单用户(单用户级别root登录不需要密码,进入之后重新设置密码) 2:多用户无网络服务 3:多用户有网络服务 4:系统未 ...
- Linux shell awk模式使用
awk的PATTERN表示方法: 1,正则表达式,格式为/regex/ 以冒号为分隔符,显示/etc/passwd以r开头的行的第一段 [root@wei awk]# awk -F: '/^r/{pr ...
- Nginx 核心配置-作为下载服务器配置
Nginx 核心配置-作为下载服务器配置 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.无限速版本的下载服务器 1>.查看主配置文件 [root@node101.yinz ...
- [转]【HttpServlet】HttpServletResponse接口 案例:完成文件下载
创建时间:6.19 & 6.24 1.案例-完成文件下载 1) 什么情况下会文件下载? 浏览器不能解析的文件就下载 *使用a标签直接指向服务器上的资源 2)什么情况下需要在服务端编写文件下载 ...