生成随机验证码,上传图片文件,解析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;
}
}

}

原文地址:https://www.cnblogs.com/csj007523/p/11442979.html

时间: 2024-10-04 00:59:12

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

Python 生成随机验证码

Python生成随机验证码 Python生成随机验证码,需要使用PIL模块. 安装: 1 pip3 install pillow 基本使用 1. 创建图片 1 2 3 4 5 6 7 8 9 from PIL import Image img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255)) # 在图片查看器中打开 # img.show()  # 保存在本地 with open('code.png','wb') as f

如何生成随机验证码

Python生成随机验证码 Python生成随机验证码,需要使用PIL模块. 安装: pip3 install pillow 基本使用 1. 创建图片 from PIL import Image img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255)) # 在图片查看器中打开 # img.show() # 保存在本地 with open('code.png','wb') as f: img.save(f,format='

python生成随机验证码

Python 生成随机验证码,需安装 PIL模块 安装: pip3 install pillow 基本使用 1,.创建图片 from PIL import Image img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255)) # 在图片查看器中打开 # img.show() # 保存在本地 with open('code.png','wb') as f: img.save(f,format='png') 2.创建画笔,用

Django中生成随机验证码

Django中生成随机验证码 1.html中a标签的设置 1 <img src="/get_validcode_img/" alt=""> 2.views中的get2.views中的getvalidcode_img设置 导入文件 1 import json 2 import os 3 import random 4 from django.contrib import auth 5 from django.shortcuts import render,

学习python:实例2.用PIL生成随机验证码

效果: 代码: # 生成随机验证码图片 import string from random import randint, sample from PIL import Image, ImageDraw, ImageFont, ImageFilter # Image 负责处理图片 # ImageDraw 画笔 # ImageFont 文字 # ImageFileter 滤镜 # 定义变量 img_size = (150,50)        # 定义画布大小 img_rgb = (255,255

生成随机验证码工具类

生成随机验证码 package com.web; //验证码生成处理类 import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.geom.Line2D; import java.awt.ima

android 客户端生成随机验证码的实现

由于项目中要用到验证码,自己找了些资料,试着就把这个验证码给做了出来,代码不是很多,比较的简单,下面给大家看看我是怎么实现该功能的: 源码地址下载:http://download.csdn.net/detail/u014608640/7268905 首先当然是写XML咯,贴上代码 <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" andr

生成随机验证码

生成随机验证码实例 import random a=[] c ='' for i in range(6): if i == random.randrange(1,4): a.append(str(random.randint(1,9))) else: temp = random.randint(65,90) a.append(chr(temp)) print a b="".join(a) print b for i in a: c += str(i) print c 输出为 ['D',

pillow实例 | 生成随机验证码

1 PIL(Python Image Library) PIL是Python进行基本图片处理的package,囊括了诸如图片的剪裁.缩放.写入文字等功能.现在,我便以生成随机验证码为例,讲述PIL的基本用法. PIL库似乎已经被人抛弃,就为更新,上次使用时竟然不能用show()直接将图片,在系统默认的图片管理器中打开.好在pillow,一个PIL的方言,将PIL继续维护了下去. 生成验证码一般需要对写入的文字进行旋转.扭曲.变色等一系列操作,才能避免计算机算法的识别. 因此定义一个生成验证码的类

struts2生成随机验证码图片

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