提取DISCUZ.NET 3.1 视频抓取头像
最近做的项目,需要把客户的照片现场抓取,在网上搜了好久,发现一些通过ACTIVEX实现的方法都很复杂,由于项目的时间限制,最后决定使用FLASH 方式抓取头像,在网上找了很多FLASH抓取头像的网站,分析实现的多程都是大同小异,最后在DISCUZ发现了FLASH抓取头像的方法,现把从中提取的代码与大家分享,希望都需要的用户有所帮助。
根据DISCUZ代码结构 提取其中的camera.js,locale.xml(这个XML文件为配置文件,其中有一些配置参数网上可以找到详细说明),在提出的过程中为了能更好的理解实现过程,我用到了FLASH逆向工程的工具,查看了camera.swf的源码结构,通过查看源码结构发现实现逻辑为:通过URL参数传递图片的保存路径通过FLASH抓取的头像为文件流的方式,之后回传给AJAX页面,在AJAX页面通过分析流的重新解码保存为图片文件,从而达到,保存头像的功能。
文件结构:default.aspx,camera.js,locale.xml,camera.swf
其中:default.aspx 页面
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CardAdd.aspx.cs" Inherits="Education_CardAdd" %>
<%@ Register TagPrefix="cc2" Namespace="MREDKJ" Assembly="MREDKJNumericBox" %>
<%@ OutputCache Duration="1" Location="none" VaryByParam="none" %>
<%@ Register src="../UserControl/Calendar.ascx" tagname="Calendar" tagprefix="uc1" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>发放会员卡</title>
<base target="_self" />
<script type="text/javascript" src="../Js/camera.js"></script>
<script type="text/javascript">
//取得随机数
function getRad()
{
var d=new Date();
var m= d .getMilliseconds();
return "&rad="+m;
}
///更新图片
///时间:2010-7-15
function updateavatar(sender, args)
{
jQuery("#hImgPath").val("<%=imgName %>");
//随机数防止页面缓存。
jQuery("#imgpath").attr("src","http://www.cnblogs.com/uploadfile/userimg/<%=imgName %>"+"?rad="+Math.random());
jQuery("#avatarctrl").hide();
}
</script>
</head>
<body style="font-size: 9pt; margin-top:0px;" text="发卡">
<form id="Form2" method="post" runat="server" enctype="multipart/form-data">
<!----基本信息开始---->
<table id="tableCardinfo" cellspacing="0" cellpadding="1" width="100%" border="1" class="TABLE1">
<tr id="showimg" >
<td align="right" width="15%" class="TD1">照片:</td>
<td class="td1">
<img id="imgpath" alt="" src="http://www.cnblogs.com/uploadfile/userimg/noavatar_large.gif" style="width:297px; height:221px; border:1px solid #000;" />
<input id="hImgPath" type="hidden" runat ="server" msg="请选择图片!" /> <!-----保存图片的路径------->
</td>
<td colspan="2" class="td1">
<!------------------摄像头抓头像开始------------时间:2010-7-13------------------------>
<div id="avatarctrl" style=" float:left;" runat="server">
<script type="text/javascript">
// avatarFlashParam 为后台组合的AJAX参数处理。
document.write(AC_FL_RunContent('width', '540', 'height', '253', 'scale', 'exactfit', 'src', '<%=avatarFlashParam %>', 'id', 'mycamera', 'name', 'mycamera', 'quality', 'high', 'bgcolor', '#ffffff', 'wmode', 'transparent', 'menu', 'false', 'swLiveConnect', 'true', 'allowScriptAccess', 'always'));
</script>
</div>
<!------------------摄像头抓头像结束------------------------------------>
</td>
</tr>
</table>
<!----基本信息结束---->
</form>
</body>
</html>
default.aspx.cs 页面主要是组合参数
public string avatarFlashParam = string.Empty;
public string imgName = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//摄像头抓头像
//时间:2010-7-15
string Username =this .txtAgentName.Text .Trim ();
string Password = "admin";//用于安全验证
string userid =Guid.NewGuid ().ToString ();
avatarFlashParam = upload.GetRootUrl("/DUTrain/") + "flash/camera.swf?nt=1&inajax=1&appid=" +
upload.MD5(Username + Password) + "&input=" +userid
+ "&ucapi=" + Server.UrlEncode(upload.GetRootUrl("/DUTrain/Education/") +
"ajaxupload.aspx");
imgName = userid + ".jpg";
}
}
接下来就是ajaxupload.aspx
//上传保存图片的类。
DanceUnionBaseCom.flashupload upload = new DanceUnionBaseCom.flashupload();
protected void Page_Load(object sender, EventArgs e)
{
string uid = upload.GetString("input").Trim();//获取FLASH返回的参数用于组合保存图片路径。
//选择图片提交
if (upload.GetString("Filename") != "" && upload.GetString("Upload") != "")
{
string strreturn=upload.UploadTempAvatar(uid);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(strreturn);
HttpContext.Current.Response.End();
return;
}
//摄像头抓取。
else
{
upload.SaveAvatar("avatar1", uid);//保存图片
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write("<?xml version=\"1.0\" ?><root><face success=\"1\"/></root>");//提交FLASH处理很重要提示是否保存成功。
HttpContext.Current.Response.End();
}
}
flashupload.cs 类
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Web.Security;
using System.Configuration;
using System.Web;
namespace DanceUnionBaseCom
{
public class flashupload
{
/// <summary>
/// 保存头像文件
/// </summary>
/// <param name="avatar"></param>
/// <param name="uid"></param>
/// <returns></returns>
public bool SaveAvatar(string avatar, string uid)
{
byte[] b = FlashDataDecode(GetString(avatar));
if (b.Length == 0)
return false;
//uid = FormatUid(uid);
string size = "";
if (avatar == "avatar1")
size = "large";
else if (avatar == "avatar2")
size = "medium";
else
size = "small";
string filename = uid + ".jpg";
string avatarFileName = "http://www.cnblogs.com/uploadfile/userimg/"+filename;
deleteFile(GetMapPath(avatarFileName));
FileStream fs = new FileStream(GetMapPath(avatarFileName), FileMode.Create);
fs.Write(b, 0, b.Length);
fs.Close();
return true;
}
/// <summary>
/// 解码Flash头像传送的数据
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
private byte[] FlashDataDecode(string s)
{
byte[] r = new byte[s.Length / 2];
int l = s.Length;
for (int i = 0; i < l; i = i + 2)
{
int k1 = ((int)s[i]) - 48;
k1 -= k1 > 9 ? 7 : 0;
int k2 = ((int)s[i + 1]) - 48;
k2 -= k2 > 9 ? 7 : 0;
r[i / 2] = (byte)(k1 << 4 | k2);
}
return r;
}
/// <summary>
/// 上传临时头像文件
/// </summary>
/// <returns></returns>
public string UploadTempAvatar(string uid)
{
string filename = uid + ".jpg";
string avatarFileName = "http://www.cnblogs.com/uploadfile/userimg/" + filename;
deleteFile (GetMapPath(avatarFileName));
HttpContext.Current.Request.Files[0].SaveAs(GetMapPath(avatarFileName));
return GetRootUrl("/uploadfile/userimg/") + filename;
}
/// <summary>
/// 获得Url或表单参数的值, 先判断Url参数是否为空字符串, 如为True则返回表单参数的值
/// </summary>
/// <param name="strName">参数</param>
/// <returns>Url或表单参数的值</returns>
public string GetString(string strName)
{
return GetString(strName, false);
}
/// <summary>
/// 获得Url或表单参数的值, 先判断Url参数是否为空字符串, 如为True则返回表单参数的值
/// </summary>
/// <param name="strName">参数</param>
/// <param name="sqlSafeCheck">是否进行SQL安全检查</param>
/// <returns>Url或表单参数的值</returns>
public string GetString(string strName, bool sqlSafeCheck)
{
if ("".Equals(GetQueryString(strName)))
return GetFormString(strName, sqlSafeCheck);
else
return GetQueryString(strName, sqlSafeCheck);
}
/// <summary>
/// 获得指定表单参数的值
/// </summary>
/// <param name="strName">表单参数</param>
/// <param name="sqlSafeCheck">是否进行SQL安全检查</param>
/// <returns>表单参数的值</returns>
public string GetFormString(string strName, bool sqlSafeCheck)
{
if (HttpContext.Current.Request.Form[strName] == null)
return "";
if (sqlSafeCheck && !IsSafeSqlString(HttpContext.Current.Request.Form[strName]))
return "unsafe string";
return HttpContext.Current.Request.Form[strName];
}
/// <summary>
/// 获得指定Url参数的值
/// </summary>
/// <param name="strName">Url参数</param>
/// <param name="sqlSafeCheck">是否进行SQL安全检查</param>
/// <returns>Url参数的值</returns>
public string GetQueryString(string strName, bool sqlSafeCheck)
{
if (HttpContext.Current.Request.QueryString[strName] == null)
return "";
if (sqlSafeCheck && !IsSafeSqlString(HttpContext.Current.Request.QueryString[strName]))
return "unsafe string";
return HttpContext.Current.Request.QueryString[strName];
}
/// <summary>
/// 检测是否有Sql危险字符
/// </summary>
/// <param name="str">要判断字符串</param>
/// <returns>判断结果</returns>
public bool IsSafeSqlString(string str)
{
return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
}
/// <summary>
/// 获得当前绝对路径
/// </summary>
/// <param name="strPath">指定的路径</param>
/// <returns>绝对路径</returns>
public string GetMapPath(string strPath)
{
if (HttpContext.Current != null)
{
return HttpContext.Current.Server.MapPath(strPath);
}
else //非web程序引用
{
strPath = strPath.Replace("/", "\\");
if (strPath.StartsWith("\\"))
{
strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');
}
return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
}
}
/// <summary>
/// 格式化Uid为9位标准格式
/// </summary>
/// <param name="uid"></param>
/// <returns></returns>
public string FormatUid(string uid)
{
return uid.PadLeft(9, '0');
}
/// <summary>
/// 获得指定Url参数的值
/// </summary>
/// <param name="strName">Url参数</param>
/// <returns>Url参数的值</returns>
public string GetQueryString(string strName)
{
return GetQueryString(strName, false);
}
/// <summary>
/// 建立文件夹
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public bool CreateDir(string name)
{
try
{
Directory.CreateDirectory(name);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 获取站点根目录URL
/// </summary>
/// <returns></returns>
public string GetRootUrl(string forumPath)
{
int port = HttpContext.Current.Request.Url.Port;
return string.Format("{0}://{1}{2}{3}",
HttpContext.Current.Request.Url.Scheme,
HttpContext.Current.Request.Url.Host.ToString(),
(port == 80 || port == 0) ? "" : ":" + port,
forumPath);
}
/// <summary>
/// MD5函数
/// </summary>
/// <param name="str">原始字符串</param>
/// <returns>MD5结果</returns>
public string MD5(string str)
{
byte[] b = Encoding.UTF8.GetBytes(str);
b = new MD5CryptoServiceProvider().ComputeHash(b);
string ret = "";
for (int i = 0; i < b.Length; i++)
ret += b[i].ToString("x").PadLeft(2, '0');
return ret;
}
//默认密钥向量
private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
/// <summary>
/// DES加密字符串
/// </summary>
/// <param name="encryptString">待加密的字符串</param>
/// <param name="encryptKey">加密密钥,要求为8位</param>
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
public string Encode(string encryptString, string encryptKey)
{
encryptKey = GetSubString(encryptKey, 8, "");
encryptKey = encryptKey.PadRight(8, ' ');
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
byte[] rgbIV = Keys;
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
}
/// <summary>
/// DES解密字符串
/// </summary>
/// <param name="decryptString">待解密的字符串</param>
/// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
public string Decode(string decryptString, string decryptKey)
{
try
{
decryptKey = GetSubString(decryptKey, 8, "");
decryptKey = decryptKey.PadRight(8, ' ');
byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
byte[] rgbIV = Keys;
byte[] inputByteArray = Convert.FromBase64String(decryptString);
DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
catch
{
return "";
}
}
/// <summary>
/// 字符串如果操过指定长度则将超出的部分用指定字符串代替
/// </summary>
/// <param name="p_SrcString">要检查的字符串</param>
/// <param name="p_Length">指定长度</param>
/// <param name="p_TailString">用于替换的字符串</param>
/// <returns>截取后的字符串</returns>
public string GetSubString(string p_SrcString, int p_Length, string p_TailString)
{
return GetSubString(p_SrcString, 0, p_Length, p_TailString);
}
/// <summary>
/// 取指定长度的字符串
/// </summary>
/// <param name="p_SrcString">要检查的字符串</param>
/// <param name="p_StartIndex">起始位置</param>
/// <param name="p_Length">指定长度</param>
/// <param name="p_TailString">用于替换的字符串</param>
/// <returns>截取后的字符串</returns>
public string GetSubString(string p_SrcString, int p_StartIndex, int p_Length, string p_TailString)
{
string myResult = p_SrcString;
Byte[] bComments = Encoding.UTF8.GetBytes(p_SrcString);
foreach (char c in Encoding.UTF8.GetChars(bComments))
{ //当是日文或韩文时(注:中文的范围:\u4e00 - \u9fa5, 日文在\u0800 - \u4e00, 韩文为\xAC00-\xD7A3)
if ((c > '\u0800' && c < '\u4e00') || (c > '\xAC00' && c < '\xD7A3'))
{
//if (System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\u0800-\u4e00]+") || System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\xAC00-\xD7A3]+"))
//当截取的起始位置超出字段串长度时
if (p_StartIndex >= p_SrcString.Length)
return "";
else
return p_SrcString.Substring(p_StartIndex,
((p_Length + p_StartIndex) > p_SrcString.Length) ? (p_SrcString.Length - p_StartIndex) : p_Length);
}
}
if (p_Length >= 0)
{
byte[] bsSrcString = Encoding.Default.GetBytes(p_SrcString);
//当字符串长度大于起始位置
if (bsSrcString.Length > p_StartIndex)
{
int p_EndIndex = bsSrcString.Length;
//当要截取的长度在字符串的有效长度范围内
if (bsSrcString.Length > (p_StartIndex + p_Length))
{
p_EndIndex = p_Length + p_StartIndex;
}
else
{ //当不在有效范围内时,只取到字符串的结尾
p_Length = bsSrcString.Length - p_StartIndex;
p_TailString = "";
}
int nRealLength = p_Length;
int[] anResultFlag = new int[p_Length];
byte[] bsResult = null;
int nFlag = 0;
for (int i = p_StartIndex; i < p_EndIndex; i++)
{
if (bsSrcString[i] > 127)
{
nFlag++;
if (nFlag == 3)
nFlag = 1;
}
else
nFlag = 0;
anResultFlag[i] = nFlag;
}
if ((bsSrcString[p_EndIndex - 1] > 127) && (anResultFlag[p_Length - 1] == 1))
nRealLength = p_Length + 1;
bsResult = new byte[nRealLength];
Array.Copy(bsSrcString, p_StartIndex, bsResult, 0, nRealLength);
myResult = Encoding.Default.GetString(bsResult);
myResult = myResult + p_TailString;
}
}
return myResult;
}
/// <summary>
/// 删除文件
/// 时间:2010-7-15
/// </summary>
/// <param name="path"></param>
public void deleteFile(string path)
{
if (File .Exists(path))
{
File.Delete(path);
}
}
}
}
效果图: