限制次数记录

                    var num =contractInfo.PlayNum;var sessionStore =window.sessionStorage.getItem(contractCode);if (num >= 10) {alert("最多只能播放10次;");return;}else{if (null ==sessionStore) {num= num + 1;alert("可以播放10次,第" + num + "次播放;");}$("#videoyoudai").prop("src", contractInfo.VideoUrl);}var yvideo = document.getElementById("videoyoudai");yvideo.addEventListener("play", function () { PlayNum(num) });//保存记录
function PlayNum(num) {var sessionStore =window.sessionStorage.getItem(contractCode);if (sessionStore == null) {window.sessionStorage.setItem(contractCode, contractCode);var data = { type: "", Name: "", Code: contractCode, playNum: num };$.ajax({type:"post",url: webapiUrl ,data: data,success: function (data) {if (data.ErrCode != 0) {alert(data.ResultMsg);}},error: function (json) {var data =eval(json);if (data != "") {alert(data.ResultMsg);}else{alert("服务器错误");}}})}}

View Code

倒计时:

//倒计时
var countdown = 60;var objText = $("#codeclick").val();
function setTime(obj) {if (countdown == 0) {obj.attr('disabled', false);obj.val(objText);countdown= 60;}else{obj.attr('disabled', true);obj.val("重新发送(" + countdown + ")");countdown--; setTimeout(function () { setTime(obj) },1000);}}

View Code

公共操作/验证的静态类

    /// <summary>///公共操作/验证的静态类/// </summary>public static partial classUtil{#region 验证格式正确性的方法#region 验证是否是手机号码格式/// <summary>///验证是否是手机号码格式///(可以验证以 13、14、15、17、18 开头的手机号格式)/// </summary>/// <param name="mobile">需要验证的手机号码</param>/// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns>public static bool IsMobile(stringmobile){returnRegex.IsMatch(mobile, RegularString.Mobile);}#endregion#region 验证是否是中国区的固定电话号码格式/// <summary>///验证是否是中国区的固定电话号码格式///(可以验证格式为"3~4位区号-7~8电话号码-1~4位分机号的中国区固定电话格式",///如:021-25887741,0755-25887751-506)/// </summary>/// <param name="phone">需要验证的固定电话号码</param>/// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns>public static bool IsPhone(stringphone){returnRegex.IsMatch(phone, RegularString.Phone);}#endregion#region 验证是否是数值类型/// <summary>///验证是否是数值类型/// </summary>/// <param name="num">需要验证的数值字符串</param>/// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns>public static bool IsDecimal(stringnum){decimalres;if (decimal.TryParse(num, outres)){return true;}return false;}#endregion#region 验证是否是数字字符串/// <summary>///验证是否是数字字符串(不带正、负号)/// </summary>/// <param name="num">要验证的数字字符串</param>/// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns>public static bool IsNumber(stringnum){if (string.IsNullOrWhiteSpace(num)){return false;}returnRegex.IsMatch(num, RegularString.Number);}#endregion#region 验证纯字母字符串/// <summary>///验证纯字母字符串/// </summary>/// <param name="str">要验证的字符串</param>/// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns>public static bool IsLetter(stringstr){returnRegex.IsMatch(str, RegularString.Letter);}#endregion#region 验证是否是带正、负号的数字字符串/// <summary>///验证是否是带正、负号的数字字符串/// </summary>/// <param name="num">要验证的字符串</param>/// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns>public static bool IsNumberSign(stringnum){returnRegex.IsMatch(num, RegularString.NumberSign);}#endregion#region 验证是否是Email地址格式/// <summary>///验证是否是Email地址格式/// </summary>/// <param name="email">输入需要验证的email地址</param>/// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns>public static bool IsEmail(stringemail){returnRegex.IsMatch(email, RegularString.Email);}#endregion#region 验证是否是IP地址/// <summary>///验证是否是IP地址///可以验证是满足IPV4格式的IP地址/// </summary>/// <param name="email">需要验证的IP地址</param>/// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns>public static bool IsIP(stringip){returnRegex.IsMatch(ip, RegularString.IP);}#endregion#region 验证是否是邮政编码/// <summary>///验证是否是邮政编码///可以验证6位数字格式的中国邮政编码/// </summary>/// <param name="source"></param>/// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns>public static bool IsPostCode(stringpostCode){//return Regex.IsMatch(postCode, @"^[0-9A-Za-z]{1,10}$", RegexOptions.IgnoreCase);returnRegex.IsMatch(postCode, RegularString.PostCode);}#endregion#region 验证是否是字母、数字、"_"/// <summary>///验证是否是字母、数字、"_"/// </summary>/// <param name="str">需要验证的字符串</param>/// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns>public static bool IsLetterNumber(stringstr){returnRegex.IsMatch(str, RegularString.LetterNumber);}#endregion#region 验证是否是汉字/// <summary>///验证是否是汉字/// </summary>/// <param name="str">需要验证的字符串</param>/// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns>public static bool IsChinese(stringstr){returnRegex.IsMatch(str, RegularString.Chinese);}#endregion#region 验证是否是正确的日期格式/// <summary>///验证是否是正确的日期格式/// </summary>/// <param name="str">要检查的字串</param>/// <returns>bool</returns>public static bool IsDateTime(stringstr){DateTime dt;if (DateTime.TryParse(str, outdt)){return true;}return false;}#endregion#region 验证文件扩展名是否图片文件/// <summary>///验证文件扩展名是否图片文件///可以验证后缀名为 jpg、jpeg、gif、png 格式的文件/// </summary>/// <param name="fileName">需要验证的文件名</param>/// <returns></returns>public static bool IsImage(stringfileName){returnRegex.IsMatch(fileName, RegularString.Image, RegexOptions.IgnoreCase);}#endregion#region 验证是否是正确的身份证号码(包括15位和18位)格式/// <summary>///验证是否是正确的身份证号码(包括15位和18位)格式/// ///公民身份号码是特征组合码,由十七位数字本体码和一位数字校验码组成,排列顺序从左至右依次为: 6位数字地址码,8位数字出生日期码,3位数字顺序码和1位数字校验码。///1、地址码:表示编码对象常住户口所在县(市、旗、区)的行政区划代码,按 GB/T 2260 的规定执行。///2、出生日期码:表示编码对象出生的年、月、日,按 * GB/T 7408 的规定执行。年、月、日代码之间不用分隔符。例:某人出生日期为 1966年10月26日,其出生日期码为 19661026。///3、顺序码:表示在同一地址码所标识的区域范围内,对同年、同月、同日出生的人编定的顺序号,顺序码的奇数分配给男性,偶数千分配给女性。///4、校验码:校验码采用ISO 7064:1983,MOD 11-2 校验码系统。///(1)十七位数字本体码加权求和公式,S = Sum(Ai * Wi), i = * 0, ... , 16 ,先对前17位数字的权求和///Ai:表示第i位置上的身份证号码数字值///Wi:表示第i位置上的加权因子///Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 1///(2)计算模 Y = mod(S, 11)///(3)通过模得到对应的校验码///Y: 0 1 2 3 4 5 6 7 8 9 10///校验码: 1 0 X 9 8 7 6 5 4 3 2///  ///另外:18位身份证与15位身份证相比,多了年数:第6位开始多了19表示完整的出生日期,多了最后一位校验码/// </summary>/// <param name="cardNum">身份证号码</param>/// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns>public static bool IsIDCard(stringcardNum){bool flag = false;  //验证结果//身份证地址编码//11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东",//41: "河南", 42: "湖北", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏",//65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外"IList<string> address = new List<string>() { "11", "12", "13", "14", "15", "21", "22", "23", "31", "32", "33", "34", "35", "36", "37","41", "42", "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "63", "64","65", "71", "81", "82", "91"};if (cardNum.Length == 15 || cardNum.Length == 18){//验证是否是数字字符串string tmpNum =cardNum;if (tmpNum.Length == 18 && string.Compare(tmpNum[17].ToString(), "x", true) == 0){tmpNum= tmpNum.Remove(17);}if(Util.IsNumber(tmpNum)){//验证身份证的地址是否正确if (address.Contains(cardNum.Remove(2))){//验证出生日期是否正确string birth = string.Empty;DateTime birthTime= newDateTime();if (cardNum.Length == 18){birth= cardNum.Substring(6, 8).Insert(6, "-").Insert(4, "-");if (DateTime.TryParse(birth, outbirthTime)){//18位的身份证号码还需要验证最后一位校验码//加权因子int[] wi = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};//校验码string[] validCode = new string[] { "1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2"};int sum = 0;for (int i = 0; i < 17; i++){sum+= int.Parse(cardNum[i].ToString()) *wi[i];}int y = -1;Math.DivRem(sum,11, outy);if (string.Compare(validCode[y], cardNum[17].ToString(), true) == 0){flag= true;}}}else{birth= cardNum.Substring(6, 6).Insert(4, "-").Insert(2, "-");if (DateTime.TryParse(birth, outbirthTime)){flag= true;}}}}}returnflag;}#endregion#region 根据身份证号码获取出生日期字符串/// <summary>///根据身份证号码获取出生日期字符串/// </summary>/// <param name="cardNum">身份证号码</param>/// <returns>返回出生日期字符串,""表示身份证号码格式有误</returns>public static string GetBirthFromIdCard(stringcardNum){string result = string.Empty;if(IsIDCard(cardNum)){if (cardNum.Length == 15){result= cardNum.Substring(6, 6).Insert(4, "-").Insert(2, "-");}else if (cardNum.Length == 18){result= cardNum.Substring(6, 8).Insert(6, "-").Insert(4, "-");}}returnresult;}#endregion#region 身份证号格式化(隐藏出生年月日)/// <summary>///身份证号格式化(隐藏出生年月日)/// </summary>/// <param name="IdCard">身份证号码</param>/// <returns></returns>public static string IdCardFormatHideBirth(stringIdCard){string strIdCard = string.Empty;if (IdCard.Length == 15){strIdCard+= IdCard.Substring(0, 6).Insert(6, "******") + IdCard.Substring(12);}else if (IdCard.Length == 18){strIdCard+= IdCard.Substring(0, 6).Insert(6, "********") + IdCard.Substring(14);}returnstrIdCard;}#endregion#region 根据身份证号码获取性别/// <summary>///根据身份证号码获取性别/// </summary>/// <param name="cardNum">身份证号码</param>/// <returns>返回代表性别的代码,"m"表示男性, "w"表示女性,""表示身份证格式有误</returns>public static string GetSexFromIdCard(stringcardNum){string result = string.Empty;int tmp = 0;if(IsIDCard(cardNum)){if (cardNum.Length == 15){tmp= int.Parse(cardNum.Substring(12));}else if (cardNum.Length == 18){tmp= int.Parse(cardNum.Substring(14, 3));}int sex = -1;Math.DivRem(tmp,2, outsex);if (sex == 0){result= "w";}else{result= "m";}}returnresult;}#endregion#region 根据身份证号码获取年龄/// <summary>///根据身份证号获取实际年龄/// </summary>/// <param name="idcard">身份证号</param>/// <returns>实际年龄</returns>public static int GetAgeFromIdCard(stringidcard){DateTime birth=StrToDateTime(GetBirthFromIdCard(idcard), DateTime.Now).Value;int age = DateTime.Now.Year -birth.Year;if (DateTime.Now.Month < birth.Month ||(DateTime.Now.Month== birth.Month && DateTime.Now.Day <birth.Day))age--;returnage;}/// <summary>///是否是符合申请条件的年龄/// </summary>/// <param name="idcard"></param>/// <param name="ageFrom">最小年龄(含)</param>/// <param name="ageTo">最大年龄(含)</param>/// <returns></returns>public static bool IsAllowAgeFromIdCard(string idcard, int ageFrom = 25, int ageTo = 58){DateTime birth=DateTime.Parse(GetBirthFromIdCard(idcard));DateTime curDate=DateTime.Now.Date;if (curDate.AddYears(-1 * ageTo) <= birth && birth <= curDate.AddYears(-1 * ageFrom)) return true;return false;}#endregion#endregion#region 通用小工具类#region 生成GUID数据,并转换为大写/// <summary>///生成GUID数据,并转换为大写/// </summary>/// <returns>返回大写的Guid字符串</returns>public static stringGetGuid(){returnGuid.NewGuid().ToString().ToUpper();}#endregion#region 生成n位随机验证码/// <summary>///生成n位随机验证码算法/// </summary>/// <param name="n">生成随机验证的位数</param>/// <returns>返回生成的验证码</returns>public static string RandomCode(int n, bool OnlyNumber = false){intnumber;charcode;string StrCode =String.Empty;Random random= newRandom(DateTime.Now.Millisecond);for (int i = 0; i < n; i++){if (!OnlyNumber){number=random.Next();if (number % 2 == 0)code= (char)('0' + (char)(number % 10));elsecode= (char)('A' + (char)(number % 26));StrCode+=code.ToString();}else{number= random.Next(0, 9);StrCode+=number.ToString();}}returnStrCode;}/// <summary>///生成随机码/// </summary>/// <param name="min"></param>/// <param name="max"></param>/// <returns></returns>public static int rand(int min, intmax){Random rd= newRandom();return (int)((max - min + 1) * rd.NextDouble() +min);}#endregion#region 计算指定时间与当前时间的间隔/// <summary>///计算指定时间与当前时间的间隔/// </summary>/// <param name="dt">指定时间</param>/// <returns>返回类似“5秒前”、“5天前”、“5周前”的格式</returns>public static stringDateToSpan(DateTime dt){if (dt != null){TimeSpan timeSpan= DateTime.Now -dt;if (timeSpan.TotalDays > 60){returndt.ToShortDateString();}else if (timeSpan.TotalDays > 30){return "1个月前";}else if (timeSpan.TotalDays > 21){return "3周前";}else if (timeSpan.TotalDays > 14){return "2周前";}else if (timeSpan.TotalDays > 7){return "1周前";}else if (timeSpan.TotalDays > 1){return string.Format("{0}天前", (int)Math.Floor(timeSpan.TotalDays));}else if (timeSpan.TotalHours > 1){return string.Format("{0}小时前", (int)Math.Floor(timeSpan.TotalHours));}else if (timeSpan.TotalMinutes > 1){return string.Format("{0}分钟前", (int)Math.Floor(timeSpan.TotalMinutes));}else{return string.Format("{0}秒钟前", (int)Math.Floor(timeSpan.TotalSeconds));}}else{return "";}}#endregion#region DateTime类型按需转换成String类型/// <summary>///把DateTime dt 转换为string类型///var=0时:转换为完整的字符串,如 2007-1-2 12:30:45 -> 20070102123045///var=1时:转换为路径字符串,如 2007-1-2 12:30:45 -> 2007/01/02123045///var=2时:转换为截止到日期的字符串,如2007-1-2 12:30:45 -> 2007/01/02/// </summary>public static string DtToStr(DateTime dt, int var){string result = string.Empty;if (var == 0){result= dt.ToString("u").Replace("-", "").Replace(":", "").Replace(" ", "").Replace("Z", "");}else if (var == 1){result= dt.ToString("u").Replace("-", "").Replace(":", "").Replace(" ", "").Replace("Z", "");result= result.Insert(4, "/").Insert(7, "/");}else{result= dt.ToString("u").Replace("-", "").Replace(":", "").Replace(" ", "").Replace("Z", "");result= result.Insert(4, "/").Insert(7, "/").Substring(0, 10);}returnresult;}#endregion#region 组织Alert字符串,不包括<scripts>标签/// <summary>///组织Alert字符串,不包括 scripts 标签/// </summary>/// <param name="msg">要显示的消息内容</param>/// <returns>返回结果字符串</returns>public static string Alert(stringmsg){return string.Format("alert(\"{0}\");", msg);}/// <summary>///组织Alert字符串,关闭消息框后跳转到指定Url地址,不包括<scripts>标签/// </summary>/// <param name="msg">要显示的消息内容</param>/// <param name="redirectUrl">要跳转到指定Url地址</param>/// <returns>返回结果字符串</returns>public static string Alert(string msg, stringredirectUrl){return string.Format("alert(\"{0}\"); window.location.href=\"{1}\";", msg, redirectUrl);}#endregion#region 组织Alert脚本字符串,包括 scripts 标签/// <summary>///组织Alert脚本字符串,包括 scripts 标签/// </summary>/// <param name="msg">要显示的消息内容</param>/// <returns>返回结果字符串</returns>public static string AlertScript(stringmsg){return string.Format("<script type=\"text/javascript\">alert(\"{0}\");</script>", msg);}/// <summary>///组织Alert脚本字符串,关闭消息框后跳转到指定Url地址,包括 scripts 标签/// </summary>/// <param name="msg">要显示的消息内容</param>/// <param name="redirectUrl">要跳转到指定Url地址</param>/// <returns>返回结果字符串</returns>public static string AlertScript(string msg, stringredirectUrl){return string.Format("<script type=\"text/javascript\">alert(\"{0}\"); window.location.href=\"{1}\";</script>", msg, redirectUrl);}#endregion#region 组织Confirm字符串,显示“确定/取消”对话框/// <summary>///组织Confirm字符串,显示“确定/取消”对话框/// </summary>/// <param name="confirmUrl">点击“确定”跳转的Url</param>/// <param name="concelUrl">点击“取消”跳转的Url</param>/// <returns>返回结果字符串</returns>public static string Confirm(string confirmUrl, stringconcelUrl){string msg = "数据已经提交成功!\\n继续提交数据?";returnConfirm(msg, confirmUrl, concelUrl);}/// <summary>///组织Confirm字符串,显示“确定/取消”对话框/// </summary>/// <param name="msg">弹出对话框的消息内容</param>/// <param name="confirmUrl">点击“确定”跳转的Url</param>/// <param name="concelUrl">点击“取消”跳转的Url</param>/// <returns>返回结果字符串</returns>public static string Confirm(string msg, string confirmUrl, stringconcelUrl){//<script type="text/javascript">if(confirm("{0}")) { window.location.href = "{1}"; } else { window.location.href = "{2}"; }</script>return string.Format("<script type=\"text/javascript\">if(confirm(\"{0}\")) { window.location.href = \"{1}\"; } else { window.location.href = \"{2}\"; }</script>", msg, confirmUrl, concelUrl);}#endregion#region 利用正则表达式去掉所有Html标签/// <summary>///利用正则表达式去掉所有Html标签/// </summary>/// <param name="strHtml">包含Html标签的字符串</param>/// <returns>返回不包含Html标签的字符串</returns>public static string FilterHtml(stringstrHtml){string result = string.Empty;if (!string.IsNullOrEmpty(strHtml)){string[] aryReg ={@"<script[^>]*?>.*?</script>",@"<(.[^>]*)>",@"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""''])(\\[""''tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",@"([\r])[\s]+",@"&(quot|#34);",@"&(amp|#38);",@"&(lt|#60);",@"&(gt|#62);",@"&(nbsp|#160);",@"&(iexcl|#161);",@"&(cent|#162);",@"&(pound|#163);",@"&(copy|#169);",@"&#(\d+);",@"-->",@"<!--.*"};string[] aryRep ={"","","","","\"","&","<",">"," ","\xa1",//chr(161),"\xa2",//chr(162),"\xa3",//chr(163),"\xa9",//chr(169),"","\r",""};result=strHtml;for (int i = 0; i < aryReg.Length; i++){Regex regex= newRegex(aryReg[i], RegexOptions.IgnoreCase);result=regex.Replace(result, aryRep[i]);}result= result.Replace("<", "").Replace(">", "").Replace("\r", "");}returnresult;}#endregion#region 获取文件的扩展名/// <summary>///获取文件的扩展名,格式为".txt"、".gif"、".docx"等/// </summary>/// <param name="fileName">文件名称(可以包含路径)</param>/// <returns>返回扩展名,格式为".txt"、".gif"、".docx"等</returns>public static string GetFileExt(stringfileName){string result = string.Empty;if (!string.IsNullOrEmpty(fileName)){int index = fileName.LastIndexOf('.');if (index > 0){result=fileName.Substring(index);}}returnresult;}#endregion#region 根据文件名判断文件类型/// <summary>///判断文件是否是图片/// </summary>/// <param name="FileName"></param>/// <returns></returns>public static bool IsImageAndPdf(stringFileName){string[] strs = FileName.Split('.');if (strs.Length > 0){string str = "*.JPG;*.JPEG;*.JPE;*.JFIF;*.BMP;*.PNG;*.TIF;*.TIFF;*.PDF;*.GIF|JPEG|*.JPG;*.JPEG;*.JPE;*.Jfif|BMP|*.BMP|PNG|*.PNG|TIFF|*.TIF;*.TIFF|PDF|*.PDF|GIF|*.GIF";string Ftype = strs[strs.Length - 1];if (str.Contains("." +Ftype.ToUpper())){return true;}}return false;}/// <summary>///是否为音视频文件。/// </summary>/// <param name="FileName"></param>/// <returns></returns>public static bool IsAudioOrVideo(stringFileName){string[] strs = FileName.Split('.');if (strs.Length > 0){string str = "*.M4A;*.MP3;*.WMA;*.RM;*.WAV;*.MIDI;*.APE;*.FLAC;*.AVI;*.RMVB;*.ASF;*.DIVX;*.MPG;*.MPEG;*.MPE;*.WMV;*.MP4;*.MKV;*.VOB;*.AAC";string Ftype = strs[strs.Length - 1];if (str.Contains("." +Ftype.ToUpper())){return true;}}return false;}#endregion#region 获取文件名/// <summary>///获取文件名/// </summary>/// <param name="fileName">文件名称(可以包含路径)</param>/// <returns>返回包含扩展名但不包含路径的文件名</returns>public static string GetFileName(stringfileName){string result =fileName;if (!string.IsNullOrEmpty(fileName)){int index = fileName.LastIndexOf('\\');if (index > 0){result= fileName.Substring(index + 1);}}returnresult;}#endregion#region 获取目录下的文件/// <summary>///获取目录下的文件/// </summary>/// <param name="folderFullName">文件目录口路径</param>/// <param name="searchPattern">搜索模式匹配的文件</param>/// <returns></returns>public static FileInfo[] GetDirectoryFiles(string folderFullName, string searchPattern = null){DirectoryInfo theFolder= newDirectoryInfo(folderFullName);if (searchPattern == null){returntheFolder.GetFiles();}returntheFolder.GetFiles(searchPattern);}#endregion#region 获取文件 哈希码public static string GetFileHashMD5(stringfileName){using (HashAlgorithm hashMD5 = newMD5CryptoServiceProvider()){using (Stream file = newFileStream(fileName, FileMode.Open, FileAccess.Read)){byte[] hash =hashMD5.ComputeHash(file);return BitConverter.ToString(hash).Replace("-", string.Empty);}}}public static string GetFileHashMD5AndLength(string fileName, out longfileLength){using (HashAlgorithm hashMD5 = newMD5CryptoServiceProvider()){using (Stream file = newFileStream(fileName, FileMode.Open, FileAccess.Read)){byte[] hash =hashMD5.ComputeHash(file);fileLength=file.Length;return BitConverter.ToString(hash).Replace("-", string.Empty);}}}public static string GetFileHashSHA1(stringfileName){using (HashAlgorithm hashSHA1 = newSHA1Managed()){using (Stream file = newFileStream(fileName, FileMode.Open, FileAccess.Read)){byte[] hash =hashSHA1.ComputeHash(file);return BitConverter.ToString(hash).Replace("-", string.Empty);}}}#endregion#region 将回车换行(\r\n)转换为Html标签中的<br />标签/// <summary>///将回车换行(\r\n)转换为Html标签中的<br />标签/// </summary>/// <param name="str">扩展方法的字符串对象</param>/// <returns>返回转换后的字符串</returns>public static string EnterToBr(stringstr){string result = string.Empty;if (!string.IsNullOrEmpty(str)){//替换回车换行,因为换行有几种标记,所以依次替换
result= str.Replace("\r\n", "<br />").Replace("\r", "<br />").Replace("\n", "<br />").Replace(" ", "&nbsp;");}returnresult;}#endregion#region 获取字符串前面部分/// <summary>///获取字符串前面部分///(此方法有bug)/// </summary>/// <param name="str">需要截取的原字符串</param>/// <param name="len">需要截取的长度</param>/// <returns>返回截取后的字符串</returns>public static string GetPreString(string str, intlen){string result = string.Empty;if (!string.IsNullOrEmpty(str)){char[] arrChar =str.ToCharArray();if (arrChar.Length <=len){result=str;}else{StringBuilder sb= newStringBuilder();for (int i = 0; i < len; i++){sb.Append(arrChar[i]);}sb.Append("...");result=sb.ToString();}}returnresult;}/// <summary>///获取字符串前面部分/// </summary>/// <param name="inputStr">输入的字符串</param>/// <param name="length">字符串需要截取的长度(包括后缀suffix的长度)</param>/// <param name="suffix">后缀suffix</param>/// <returns>返回截取后的字符串</returns>public static string GetSubString(string inputStr, int length, stringsuffix){string tempStr = inputStr.Substring(0, (inputStr.Length < length) ?inputStr.Length : length);if (Regex.Replace(tempStr, "[\u4e00-\u9fa5]", "aa", RegexOptions.IgnoreCase).Length <=length){returntempStr;}for (int i = tempStr.Length; i >= 0; i--){tempStr= tempStr.Substring(0, i);if (Regex.Replace(tempStr, "[\u4e00-\u9fa5]", "zz", RegexOptions.IgnoreCase).Length <= length -suffix.Length){return tempStr +suffix;}}returnsuffix;}#endregion#region 获取字符串长度(中文算两个字符)/// <summary>///获取字符串长度(中文算两个字符)/// </summary>/// <param name="str"></param>/// <returns></returns>public static int ChineseLength(stringstr){if (string.IsNullOrEmpty(str)) return 0;int lenTotal =str.Length;intasc;for (int i = 0; i < str.Length; i++){//asc = Convert.ToChar(str.Substring(i, 1));asc =str[i];if (asc < 0 || asc > 127)lenTotal= lenTotal + 1;}returnlenTotal;}#endregion#region 从字符串的指定位置截取指定长度的子字符串/// <summary>///从字符串的指定位置截取指定长度的子字符串/// </summary>/// <param name="str">原字符串</param>/// <param name="startIndex">子字符串的起始位置</param>/// <param name="length">子字符串的长度</param>/// <returns>子字符串</returns>public static string CutString(string str, int startIndex, intlength){if (startIndex >= 0){if (length < 0){length= length * -1;if (startIndex - length < 0){length=startIndex;startIndex= 0;}else{startIndex= startIndex -length;}}if (startIndex >str.Length){return "";}}else{if (length < 0){return "";}else{if (length + startIndex > 0){length= length +startIndex;startIndex= 0;}else{return "";}}}if (str.Length - startIndex <length){length= str.Length -startIndex;}returnstr.Substring(startIndex, length);}#endregion#region DecodeBase64/// <summary>///主要用于为字段"MerPriv"解密/// </summary>/// <param name="strEncStr"></param>/// <returns></returns>public static string DecodeBase64(stringstrEncStr){string reDecStr = string.Empty;byte[] bytes =Convert.FromBase64String(strEncStr);try{reDecStr=Encoding.UTF8.GetString(bytes);}catch(Exception ex){throwex;}returnreDecStr;}#endregion#region 类型与Byte数组转换/// <summary>///序列化一个对象/// </summary>/// <param name="entity"></param>/// <returns></returns>public static byte[] SerializeBinary(objectentity){if (entity == null){return null;}try{MemoryStream ms= newMemoryStream();BinaryFormatter bf= newBinaryFormatter();bf.Serialize(ms, entity);returnms.ToArray();}catch(Exception ex){throwex;}}public static T DeserializeBinary<T>(byte[] bytes){if (bytes == null){return default(T);}try{MemoryStream ms= newMemoryStream(bytes);BinaryFormatter bf= newBinaryFormatter();return(T)bf.Deserialize(ms);}catch{return default(T);}}#endregion#region 读取文件到字节数组中/// <summary>///读取文件到字节数组中/// </summary>/// <param name="path">文件路径</param>/// <returns></returns>public static byte[] ReadFileTobytes(stringpath){byte[] bts = new byte[0];try{FileStream fs= newFileStream(path, FileMode.Open);long size =fs.Length;bts= new byte[size];fs.Read(bts,0, bts.Length);fs.Close();returnbts;}catch(Exception){returnbts;}}public static sbyte[] ReadFileToSbytes(stringpath){FileStream fs= newFileStream(path, FileMode.Open);long size =fs.Length;byte[] bts = new byte[size];fs.Read(bts,0, bts.Length);fs.Close();sbyte[] sbyteArray = new sbyte[bts.Length];for (int i = 0; i < sbyteArray.Length; i++){sbyteArray[i]= unchecked((sbyte)bts[i]);}returnsbyteArray;}#endregion#region  byte数组转化成sbyte/// <summary>///byte数组转化成sbyte/// </summary>/// <param name="byteArray"></param>/// <returns></returns>public static sbyte[] ConvertByteToSbyte(byte[] byteArray){sbyte[] sbyteArray = new sbyte[byteArray.Length];for (int i = 0; i < sbyteArray.Length; i++){sbyteArray[i]= unchecked((sbyte)byteArray[i]);}returnsbyteArray;}#endregion#region 去除字符串中的空格/// <summary>///去除字符串中的空格/// </summary>/// <param name="text"></param>/// <returns></returns>public static string TrimSpace(stringtext){if (string.IsNullOrWhiteSpace(text))return string.Empty;return Regex.Replace(text, @"\s", "");}#endregion#region 去除重复项/// <summary>///去除重复项/// </summary>/// <typeparam name="TSource"></typeparam>/// <typeparam name="TKey"></typeparam>/// <param name="source"></param>/// <param name="keySelector"></param>/// <returns></returns>public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey>keySelector){HashSet<TKey> seenKeys = new HashSet<TKey>();foreach (TSource element insource){if(seenKeys.Add(keySelector(element))){yield returnelement;}}}#endregion#endregion#region 简单封装部分#region 实例化SMTP服务/// <summary>///实例化SMTP服务/// </summary>/// <returns></returns>public staticSMTP GetSmtpInstance(){string smtpServer = System.Web.Configuration.WebConfigurationManager.AppSettings["MailSmtpServer"];string userName = System.Web.Configuration.WebConfigurationManager.AppSettings["MailUserName"];string password = System.Web.Configuration.WebConfigurationManager.AppSettings["MailPassword"];return newSMTP(userName, smtpServer, userName, password);}#endregion#region 根据Email地址获取Email的登录地址/// <summary>///根据Email地址获取Email的登录地址/// </summary>/// <param name="mailAddr">Email地址</param>/// <returns></returns>public static string GetMailLogin(stringemail){if (string.IsNullOrEmpty(email)){throw new ArgumentException("邮箱地址不能为空");}email=email.Trim();string mailLogin = string.Empty;if(Util.IsEmail(email)){switch (email.Substring(email.IndexOf('@') + 1).ToLower()){case "126.com":mailLogin= "http://mail.126.com";break;case "163.com":mailLogin= "http://mail.163.com";break;case "yeah.net":mailLogin= "http://mail.yeah.net/";break;case "sohu.com":case "focus.cn":case "chinaren.com":case "sogou.com":mailLogin= "http://passport.sohu.com/indexAction.action";break;case "sina.cn":case "sina.com":mailLogin= "http://mail.sina.com/";break;case "yahoo.cn":case "yahoo.com.cn":mailLogin= "http://mail.cn.yahoo.com";break;case "qq.com":mailLogin= "http://mail.qq.com";break;}}returnmailLogin;}#endregion#endregion#region 类型转换/// <summary>///字符串转换为整型,如果能转换返回转换后的整型数值,如果不能转换就返回传进来的默认参数defVal的值/// </summary>/// <param name="val">要转换为整型的字符串</param>/// <param name="defVal">转换失败时的默认值</param>/// <returns></returns>public static int? StrToInt(string val, int?defVal){if (string.IsNullOrWhiteSpace(val)) returndefVal;intresult;if (int.TryParse(val, outresult)){returnresult;}else{returndefVal;}}/// <summary>///字符串转换为长整型,如果能转换返回转换后的长整型数值,如果不能转换就返回传进来的默认参数defVal的值/// </summary>/// <param name="val">要转换为长整型的字符串</param>/// <param name="defVal">转换失败时的默认值</param>/// <returns></returns>public static long? StrToLong(string val, long?defVal){if (string.IsNullOrWhiteSpace(val)) returndefVal;longresult;if (long.TryParse(val, outresult)){returnresult;}else{returndefVal;}}/// <summary>///string转换为double/// </summary>/// <param name="val"></param>/// <param name="defVal"></param>/// <returns></returns>public static double? StrToDouble(string val, double?defVal){if (string.IsNullOrWhiteSpace(val)) returndefVal;doubleresult;if (double.TryParse(val, outresult)){returnresult;}else{returndefVal;}}public static string DoubleToStr(double? val, string format = "f2"){if (val == null) return string.Empty;returnval.Value.ToString(format);}/// <summary>///字符串转换为decimal,如果能转换返回转换后的decimal数值,如果不能转换就返回传进来的默认参数defVal的值/// </summary>/// <param name="val">要转换为decimal的字符串</param>/// <param name="defVal">转换失败时的默认值</param>/// <returns></returns>public static decimal? StrToDecimal(string val, decimal?defVal){if (string.IsNullOrWhiteSpace(val)) returndefVal;decimalresult;if (decimal.TryParse(val, outresult)){returnresult;}else{returndefVal;}}public static string DecimalToStr(decimal? val, string format = "f2"){if (val == null) return string.Empty;returnval.Value.ToString(format);}/// <summary>///字符串转换为日期类型,如果能转换返回转换后的日期类型,如果不能转换就返回传进来的默认参数defVal的值/// </summary>/// <param name="val">要转换为日期类型的字符串</param>/// <param name="defVal">转换失败时的默认值</param>/// <returns></returns>public static DateTime? StrToDateTime(string val, DateTime?defVal){if (string.IsNullOrWhiteSpace(val)) returndefVal;DateTime result;if (DateTime.TryParse(val, outresult)){returnresult;}else{returndefVal;}}public static DateTime? StrToDateTimeByyyyyMMdd(string val, DateTime?defVal){if (string.IsNullOrWhiteSpace(val)) returndefVal;DateTime result;if (DateTime.TryParseExact(val, "yyyyMMdd HH:mm:ss",null, System.Globalization.DateTimeStyles.None, outresult)){returnresult;}else{returndefVal;}}public static DateTime? StrToDateTimeBy_yyyyMMdd(stringval){if (string.IsNullOrWhiteSpace(val) || val.Length<8) return null;DateTime? dt = null;string yStr = val.Substring(0,4);string mStr = val.Substring(4, 2);string dStr = val.Substring(6,2);try{dt= new DateTime(int.Parse(yStr), int.Parse(mStr), int.Parse(dStr));}catch{ }returndt;}public static string DateTimeToStr(DateTime? val, string format = "yyyy-MM-dd"){if (null == val) return string.Empty;returnval.Value.ToString(format);}public static stringDateTimeToStr(DateTime val){return val.ToString("yyyy-MM-dd");}#endregion#region 克隆属性/// <summary>///克隆属性的值/// </summary>/// <param name="fromObject"></param>/// <param name="toObject"></param>public static void Clone(object fromObject, objecttoObject){PropertyInfo[] properties=fromObject.GetType().GetProperties();Type newType=toObject.GetType();foreach (PropertyInfo pInfo inproperties){if (!pInfo.CanRead) continue;PropertyInfo nInfo=newType.GetProperty(pInfo.Name);if (null == nInfo) continue;if (!nInfo.CanWrite) continue;nInfo.SetValue(toObject, pInfo.GetValue(fromObject));}}#endregion#region 中文大写/// <summary>///返回中文数字 ,如壹佰元整/// </summary>/// <param name="valIn"></param>/// <param name="strType">0返回金额写法,1返回数量写法</param>/// <returns></returns>public static string GetChineseNum(decimal valIn, int strType = 0){stringm_1, m_2, m_3, m_4, m_5, m_6, m_7, m_8, m_9;string numNum = "0123456789.";string numChina = "零壹贰叁肆伍陆柒捌玖点";string numChinaWeigh = "个拾佰仟万拾佰仟亿拾佰仟万";//m_1.Format("%.2f",   atof(m_1));m_1 = valIn.ToString("f2");m_2=m_1;m_3= m_4 = "";//m_2:1234-> 壹贰叁肆for (int i = 0; i < 11; i++){//m_2=m_2.Replace(numNum.Mid(i,   1),   numChina.Mid(i   *   2,   2));m_2 = m_2.Replace(numNum.Substring(i, 1), numChina.Substring(i, 1));}//m_3:佰拾万仟佰拾个int iLen =m_1.Length;if (iLen > 16){m_8= m_9 = "越界错!";throw new Exception("数字太大,超出处理范围");}if (m_1.IndexOf('.') > 0)iLen= m_1.IndexOf('.');for (int j = iLen; j >= 1; j--){m_3+= numChinaWeigh.Substring(j - 1, 1);}//m_4:2行+3行for (int i = 0; i < m_3.Length; i++){m_4+= m_2.Substring(i, 1) + m_3.Substring(i, 1);}//m_5:4行去"0"后拾佰仟
m_5=m_4;m_5= m_5.Replace("零拾", "");m_5= m_5.Replace("零佰", "");m_5= m_5.Replace("零仟", "");//m_6:00-> 0,000-> 0
m_6=m_5;for (int i = 0; i < iLen; i++)m_6= m_6.Replace("零零", "");//m_7:6行去亿,万,个位"0"m_7 =m_6;m_7= m_7.Replace("亿零万零", "亿零");m_7= m_7.Replace("亿零万", "亿零");m_7= m_7.Replace("零亿", "亿");m_7= m_7.Replace("零万", "");if (m_7.Length > 2)m_7= m_7.Replace("零个", "");//m_8:7行+2行小数-> 数目m_8 =m_7;m_8= m_8.Replace("", "");if (m_2.Substring(m_2.Length - 3, 3) != "点零零")m_8+= m_2.Substring(m_2.Length - 3, 3);//m_9:7行+2行小数-> 价格m_9 =m_7;m_9= m_9.Replace("", "");if (m_2.Substring(m_2.Length - 3, 3) != "点零零"){m_9+= m_2.Substring(m_2.Length - 2, 2);m_9= m_9.Insert(m_9.Length - 1, "");m_9+= "";}else m_9 += "";if (m_9 != "零元整")m_9= m_9.Replace("零元", "");m_9= m_9.Replace("零分", "");if (strType == 1) //数量returnm_8;elsereturnm_9;}#endregion#region 日期转中文/// <summary>///日期转中文/// </summary>/// <param name="strDate">日期</param>/// <returns></returns>public static string GetChineseDate(stringstrDate){char[] strChinese = new char[] {'','','','','','','','','','',''};StringBuilder result= newStringBuilder();//// 依据正则表达式判断参数是否正确//Regex theReg = new Regex(@"(d{2}|d{4})(/|-)(d{1,2})(/|-)(d{1,2})");if (!string.IsNullOrEmpty(strDate)){//将数字日期的年月日存到字符数组str中string[] str = null;if (strDate.Contains("-")){str= strDate.Split('-');}else if (strDate.Contains("/")){str= strDate.Split('/');}//str[0]中为年,将其各个字符转换为相应的汉字for (int i = 0; i < str[0].Length; i++){result.Append(strChinese[int.Parse(str[0][i].ToString())]);}result.Append("");//转换月int month = int.Parse(str[1]);int MN1 = month / 10;int MN2 = month % 10;if (MN1 > 1){result.Append(strChinese[MN1]);}if (MN1 > 0){result.Append(strChinese[10]);}if (MN2 != 0){result.Append(strChinese[MN2]);}result.Append("");//转换日int day = int.Parse(str[2]);int DN1 = day / 10;int DN2 = day % 10;if (DN1 > 1){result.Append(strChinese[DN1]);}if (DN1 > 0){result.Append(strChinese[10]);}if (DN2 != 0){result.Append(strChinese[DN2]);}result.Append("");}else{throw newArgumentException();}returnresult.ToString();}#endregion#region 程序当前路径public static stringBaseDirectory{get{string _appPath =AppDomain.CurrentDomain.BaseDirectory;if (!_appPath.EndsWith(@"\")) _appPath = _appPath + @"\";return_appPath;}}#endregion#region 获取Post请求参数/// <summary>///功能描述:获取Post请求参数///创 建 人:zhoupei///创建日期:2015-05-20/// </summary>/// <param name="strParameterName">参数名</param>/// <param name="strDefaultValue">默认值</param>/// <returns></returns>public static string GetPostParameter(string strParameterName, stringstrDefaultValue){string strParameterValue = HttpContext.Current.Request.Form[strParameterName] == null?strDefaultValue: HttpUtility.UrlDecode(HttpContext.Current.Request.Form[strParameterName], Encoding.UTF8);returnstrParameterValue;}/// <summary>///不同资金平台 对应 不同的合同名称/// </summary>/// <param name="FundGuid">资金平台GUID</param>/// <returns></returns>public static string GetContactName(stringFundGuid){string name = "";switch(FundGuid){caseConstValue.FundType_1:caseConstValue.FundType_2:caseConstValue.FundType_5:caseConstValue.FundType_6:caseConstValue.FundType_7:caseConstValue.FundType_8:caseConstValue.FundType_9:caseConstValue.FundType_10:caseConstValue.FundType_14:caseConstValue.FundType_15:caseConstValue.FundType_24:name= "小额借款服务合同";break;caseConstValue.FundType_3:name= "委托贷款合同";break;caseConstValue.FundType_4:caseConstValue.FundType_11:caseConstValue.FundType_13:name= "信托借款合同";break;caseConstValue.FundType_12:name= "杭州银行股份有限公司个人小额代理贷款借款合同";break;caseConstValue.FundType_20:caseConstValue.FundType_JuYouCai:name= "小额借款咨询服务合同";break;default:name= "小额借款服务合同";break;}returnname;}#endregion#region 清理手机及座机号码格式/// <summary>///清理手机及座机号码格式,去掉 - 、17909前缀等/// </summary>/// <param name="phoneNo"></param>/// <returns></returns>public static string ClearPhoneNo(stringphoneNo){if (string.IsNullOrEmpty(phoneNo)) return "";phoneNo=phoneNo.Trim();phoneNo= phoneNo.TrimEnd(' ', '-');phoneNo= phoneNo.TrimEnd(' ', '-');if (phoneNo.StartsWith("9")) phoneNo = phoneNo.Substring(1);if (phoneNo.StartsWith("17909")) phoneNo = phoneNo.Substring(5);if (phoneNo.StartsWith("0") && Util.IsMobile(phoneNo.Substring(1))){phoneNo= phoneNo.Substring(1);}else{if (phoneNo.Contains("-")){if (!phoneNo.StartsWith("0")) phoneNo = "0" +phoneNo;}else{phoneNo= phoneNo.Replace("-", "");if (!phoneNo.StartsWith("0") && phoneNo.Length > 8 && !Util.IsMobile(phoneNo)){phoneNo= "0" +phoneNo;}}}phoneNo= phoneNo.Replace("-", "");returnphoneNo;}#endregion#region 判断手机号是属于哪个运营商的/// <summary>///判断手机号是属于哪个运营商的/// </summary>/// <param name="phoneNo"></param>/// <returns></returns>public static string CommunicationsOperatorName(stringphoneNo){if (string.IsNullOrWhiteSpace(phoneNo) || phoneNo.Length != 11)return "手机号为空或者长度不对";phoneNo= phoneNo.Substring(0, 3);if(ConstValue.CommunicationsOperator_DIANXIN.Contains(phoneNo))return "中国电信";if(ConstValue.CommunicationsOperator_LIANTONG.Contains(phoneNo))return "中国联通";if(ConstValue.CommunicationsOperator_YIDONG.Contains(phoneNo))return "中国移动";return "找不到对应的通讯运营商";}#endregion#region 将传入的字符串中间部分字符替换成特殊字符/// <summary>///将传入的字符串中间部分字符替换成特殊字符/// </summary>/// <param name="value">需要替换的字符串</param>/// <param name="startLen">前保留长度</param>/// <param name="endLen">尾保留长度</param>/// <param name="replaceChar">特殊字符</param>/// <returns>被特殊字符替换的字符串</returns>public static string ReplaceWithSpecialChar(string value, int startLen = 4, int endLen = 4, char specialChar = '*'){try{if (string.IsNullOrWhiteSpace(value))return "";int lenth = value.Length - startLen -endLen;if (lenth <= 0)return "";string replaceStr =value.Substring(startLen, lenth);string specialStr = string.Empty;for (int i = 0; i < replaceStr.Length; i++){specialStr+=specialChar;}value=value.Replace(replaceStr, specialStr);}catch(Exception){throw;}returnvalue;}#endregion/// <summary>///根据枚举获取对应属性描述/// </summary>/// <param name="enumValue"></param>/// <returns></returns>public static stringGetEnumDescription(Enum enumValue){string str =enumValue.ToString();System.Reflection.FieldInfo field=enumValue.GetType().GetField(str);object[] objs = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);if (objs == null || objs.Length == 0) returnstr;System.ComponentModel.DescriptionAttribute da= (System.ComponentModel.DescriptionAttribute)objs[0];returnda.Description;}#region 根据经纬度计算两地距离//地球半径,单位米private const double EARTH_RADIUS = 6378137;/// <summary>///计算两点位置的距离,返回两点的距离,单位:米///该公式为GOOGLE提供,误差小于0.2米/// </summary>/// <param name="lng1">第一点经度</param>/// <param name="lat1">第一点纬度</param>        /// <param name="lng2">第二点经度</param>/// <param name="lat2">第二点纬度</param>/// <returns></returns>public static double GetDistance(double lng1, double lat1, double lng2, doublelat2){double radLat1 =Rad(lat1);double radLng1 =Rad(lng1);double radLat2 =Rad(lat2);double radLng2 =Rad(lng2);double a = radLat1 -radLat2;double b = radLng1 -radLng2;double result = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) + Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2))) *EARTH_RADIUS;returnresult;}/// <summary>///经纬度转化成弧度/// </summary>/// <param name="d"></param>/// <returns></returns>private static double Rad(doubled){return (double)d * Math.PI /180d;}#endregion#region 压缩图片/// <summary>///压缩图片/// </summary>/// <param name="iSource"></param>/// <param name="outPath">输出新的图片路径</param>/// <param name="flag">压缩倍数 将图片按百分比压缩,flag取值1到100,越小压缩比越大</param>/// <returns></returns>public static bool YaSuo(Image iSource, string outPath, int flag,int? maxFBL=null){Image tmp=iSource;ImageFormat tFormat=iSource.RawFormat;EncoderParameters ep= newEncoderParameters();long[] qy = new long[1];qy[0] =flag;EncoderParameter eParam= newEncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);ep.Param[0] =eParam;try{if (iSource != null && maxFBL != null && maxFBL > 0 && (iSource.Height > maxFBL || iSource.Width >maxFBL)){double width =iSource.Width;double height =iSource.Height;if (width >maxFBL){width= 1000;height= iSource.Height / (iSource.Width /1000d);}if (height >maxFBL){height= 1000;width= iSource.Width / (iSource.Height / 1000);}tmp= Util.ResizeImage(iSource, new Size((int)width, (int)height));}ImageCodecInfo[] arrayICI=ImageCodecInfo.GetImageDecoders();ImageCodecInfo jpegICIinfo= null;for (int x = 0; x < arrayICI.Length; x++){if (arrayICI[x].FormatDescription.Equals("JPEG")){jpegICIinfo=arrayICI[x];break;}}if (jpegICIinfo != null)tmp.Save(outPath, jpegICIinfo, ep);elsetmp.Save(outPath, tFormat);return true;}catch(Exception ex){//StreamWriter sw = new StreamWriter(@"C:\\ImgYasuo.txt", true, Encoding.UTF8);//sw.WriteLine(ex.StackTrace);//sw.Flush();//sw.Close();throwex;//return false;
}finally{iSource.Dispose();tmp.Dispose();}}/// <summary>///压缩图片并返回高度/// </summary>/// <param name="iSource"></param>/// <param name="outPath">输出新的图片路径</param>/// <param name="flag">压缩倍数 将图片按百分比压缩,flag取值1到100,越小压缩比越大</param>/// <returns></returns>public static bool YaSuo(Image iSource, string outPath, int flag, ref int totalint, int? maxFBL = null){Image tmp=iSource;ImageFormat tFormat=iSource.RawFormat;EncoderParameters ep= newEncoderParameters();long[] qy = new long[1];qy[0] =flag;EncoderParameter eParam= newEncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);ep.Param[0] =eParam;try{if (iSource != null && maxFBL != null && maxFBL > 0 && (iSource.Height > maxFBL || iSource.Width >maxFBL)){double width =iSource.Width;double height =iSource.Height;if (width >maxFBL){width= 1000;height= iSource.Height / (iSource.Width /1000d);}if (height >maxFBL){height= 1000;width= iSource.Width / (iSource.Height / 1000);}tmp= ResizeImage(iSource, new Size((int)width, (int)height));totalint= totalint + (int)height;}else{double height =iSource.Height;totalint= totalint + (int)height;}ImageCodecInfo[] arrayICI=ImageCodecInfo.GetImageDecoders();ImageCodecInfo jpegICIinfo= null;for (int x = 0; x < arrayICI.Length; x++){if (arrayICI[x].FormatDescription.Equals("JPEG")){jpegICIinfo=arrayICI[x];break;}}if (jpegICIinfo != null)tmp.Save(outPath, jpegICIinfo, ep);elsetmp.Save(outPath, tFormat);return true;}catch{return false;}finally{iSource.Dispose();}}public staticSystem.Drawing.Image ResizeImage(System.Drawing.Image imgToResize, Size size){//获取图片宽度int sourceWidth =imgToResize.Width;//获取图片高度int sourceHeight =imgToResize.Height;float nPercent = 0;float nPercentW = 0;float nPercentH = 0;//计算宽度的缩放比例nPercentW = ((float)size.Width / (float)sourceWidth);//计算高度的缩放比例nPercentH = ((float)size.Height / (float)sourceHeight);if (nPercentH <nPercentW)nPercent=nPercentH;elsenPercent=nPercentW;//期望的宽度int destWidth = (int)(sourceWidth *nPercent);//期望的高度int destHeight = (int)(sourceHeight *nPercent);Bitmap b= newBitmap(destWidth, destHeight);Graphics g=Graphics.FromImage((System.Drawing.Image)b);g.InterpolationMode=InterpolationMode.HighQualityBicubic;//绘制图像g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);g.Dispose();return(System.Drawing.Image)b;}#endregion#region 合成图片/// <summary>  ///合成图片/// </summary>  /// <param name="fileFoldUrl">文件夹url</param>  /// <param name="fileName">文件名</param>  /// <param name="_alMemo">要合成的每张图片的大小数组</param>  /// <param name="_width">合成后的宽度</param>  /// <param name="_height">合成后的高度</param>  public static void tphc(string fileFoldUrl, stringfileName, FileInfo[] files){int iHeight = 0;ArrayList _alMemo= newArrayList();foreach (var item infiles){var tmp = fileFoldUrl + Guid.NewGuid().ToString().ToUpper() + ".jpg";YaSuo(Image.FromFile(item.FullName), tmp,50, ref iHeight, 1080);//Image img = Image.FromFile(item.FullName);//iHeight = iHeight + img.Height;//img.Dispose();FileStream fs = newFileStream(tmp, FileMode.Open);byte[] inby = new byte[(int)fs.Length];fs.Read(inby,0, inby.Length);fs.Close();fs.Dispose();_alMemo.Add(inby);if(File.Exists(tmp)) File.Delete(tmp);}byte[] tp = get_tphcMemo(_alMemo, 1024, iHeight);view_picture(fileFoldUrl, fileName, tp);}/// <summary>///压缩图片并返回高度/// </summary>/// <param name="iSource"></param>/// <param name="outPath">输出新的图片路径</param>/// <param name="flag">压缩倍数 将图片按百分比压缩,flag取值1到100,越小压缩比越大</param>/// <returns></returns>//public static bool YaSuo(Image iSource, string outPath, int flag, ref int totalint, int? maxFBL = null)//{//Image tmp = iSource;//ImageFormat tFormat = iSource.RawFormat;//EncoderParameters ep = new EncoderParameters();//long[] qy = new long[1];//qy[0] = flag;//EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);//ep.Param[0] = eParam;//try//{//if (iSource != null && maxFBL != null && maxFBL > 0 && (iSource.Height > maxFBL || iSource.Width > maxFBL))//{//double width = iSource.Width;//double height = iSource.Height;//if (width > maxFBL)//{//width = 1000;//height = iSource.Height / (iSource.Width / 1000d);//}//if (height > maxFBL)//{//height = 1000;//width = iSource.Width / (iSource.Height / 1000);//}//tmp = ResizeImage(iSource, new Size((int)width, (int)height));//totalint = totalint + (int)height;//}//else//{//double height = iSource.Height;//totalint = totalint + (int)height;//}//ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageDecoders();//ImageCodecInfo jpegICIinfo = null;//for (int x = 0; x < arrayICI.Length; x++)//{//if (arrayICI[x].FormatDescription.Equals("JPEG"))//{//jpegICIinfo = arrayICI[x];//break;//}//}//if (jpegICIinfo != null)//tmp.Save(outPath, jpegICIinfo, ep);//else//tmp.Save(outPath, tFormat);//return true;//}//catch//{//return false;//}//finally//{//iSource.Dispose();//}//}/// <summary>  ///获取合成图片后的字节大小/// </summary>  /// <param name="_al">要合成的每张图片的大小数组</param>  /// <param name="_width">合成后的宽度</param>  /// <param name="_height">合成后的高度</param>  /// <returns>byte[]</returns>  private static byte[] get_tphcMemo(ArrayList _al, int _width, int_height){byte[] tp = null;//MemoryStreamMemoryStream ms = null;MemoryStream imgms= null;//BitmapBitmap bmp = null;//imageSystem.Drawing.Image img = null;//GraphicsGraphics gp = null;try{ms= newMemoryStream();//if (!string.IsNullOrWhiteSpace(strText)) _height += 100;
bmp= newBitmap(_width, _height);bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);img=System.Drawing.Image.FromStream(ms);int i_top = 0;gp=Graphics.FromImage(img);gp.Clear(Color.White);for (int pic_i = 0; pic_i < _al.Count; pic_i++){MemoryStream ms1= new MemoryStream(((byte[])_al[pic_i]));System.Drawing.Image img1=System.Drawing.Image.FromStream(ms1);Bitmap bmp1= newBitmap(img1);Rectangle rtl= new Rectangle(0, i_top, bmp1.Width, bmp1.Height);gp.DrawImage(bmp1, rtl,0, 0, bmp1.Width, bmp1.Height, GraphicsUnit.Pixel);i_top+=bmp1.Height;ms1.Dispose();img1.Dispose();bmp1.Dispose();}gp.Dispose();imgms= newMemoryStream();img.Save(imgms, img.RawFormat);imgms.Position= 0;tp= new byte[imgms.Length];imgms.Read(tp,0, Convert.ToInt32(imgms.Length));returntp;}catch(Exception ex){throw newException(ex.Message);}}/// <summary>  ///保存图片/// </summary>  /// <param name="fileFoldUrl">文件夹url</param>  /// <param name="fileName">文件名</param>  /// <param name="zp">文件的字节数组</param>  public static void view_picture(string fileFoldUrl, string fileName, byte[] zp){MemoryStream ms= newMemoryStream(zp);Bitmap btp= newBitmap(ms);DirectoryInfo dti= newDirectoryInfo(fileFoldUrl);string fileUrl = fileFoldUrl +fileName;btp.Save(fileUrl);}#endregion/// <summary>///类型为AN或ANC的数据项左对齐的,位数不足在右面用半角空格补齐。类型为N的数据项是右对齐的,并在左面用0补齐。///所有数据项不能为空,无法填报时用空格填充。空格统一指ASCII编码0X20对应的字符。///对于ANC型数据项,要求将数据项前、中的空格以及编码范围之外的其他字符去掉。///数据项长度均指字节数。/// </summary>/// <param name="str">字符串</param>/// <param name="length">字节长度</param>/// <param name="DataType">数据类型(ANC/AN/N)</param>/// <returns></returns>public static string ANC_String(string str, int length, stringDataType){if (!string.IsNullOrWhiteSpace(str)){returnstr;}string strSpace =Space();int str_length = 0;if (str != null){if (str.Length >=length){str= str.Substring(0, length);returnstr;}str= str.Replace(" ", "").Replace(" ", "");str_length=Encoding.Default.GetBytes(str).Count();}if (length <str_length){for (int i = 0; i < length; i++){int endlength = Encoding.Default.GetBytes(str.Substring(0, i)).Count();if (endlength ==length){str= str.Substring(0, i);returnstr;}if (endlength >length){str= str.Substring(0, i - 1);str_length=Encoding.Default.GetBytes(str).Count();break;}}}if (length >str_length){if (DataType.ToUpper().Trim() == "ANC" || DataType.ToUpper().Trim() == "AN"){for (int i = 1; i < length - str_length + 1; i++){str= str +strSpace;}}else if (DataType.ToUpper().Trim() == "N"){for (int i = 1; i < length - str_length + 1; i++){str= "0" +str;}}}returnstr;}/// <summary>///返回半角空格/// </summary>/// <returns></returns>private static stringSpace(){int AscToInt = Convert.ToInt32("0x20", 16);byte[] bt = new byte[] { (byte)AscToInt };returnEncoding.ASCII.GetString(bt);}/// <summary>///图片转为PDF/// </summary>/// <param name="jpgfile"></param>/// <param name="pdf"></param>/// <param name="keyword">添加隐藏文字</param>public static void ConvertJPG2PDF(string jpgfile, string pdf,string keyword=""){var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25);using (var stream = newFileStream(pdf, FileMode.Create, FileAccess.Write, FileShare.None)){iTextSharp.text.pdf.PdfWriter Writer=iTextSharp.text.pdf.PdfWriter.GetInstance(document, stream);document.Open();using (var imageStream = newFileStream(jpgfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)){var image =iTextSharp.text.Image.GetInstance(imageStream);if (image.Height > iTextSharp.text.PageSize.A4.Height - 25){image.ScaleToFit(iTextSharp.text.PageSize.A4.Width- 25, iTextSharp.text.PageSize.A4.Height - 25);}else if (image.Width > iTextSharp.text.PageSize.A4.Width - 25){image.ScaleToFit(iTextSharp.text.PageSize.A4.Width- 25, iTextSharp.text.PageSize.A4.Height - 25);}image.Alignment=iTextSharp.text.Image.ALIGN_MIDDLE;document.Add(image);}if(!string.IsNullOrWhiteSpace(keyword)){iTextSharp.text.pdf.BaseFont bfChinese= iTextSharp.text.pdf.BaseFont.CreateFont("C:\\Windows\\Fonts\\STSONG.TTF", iTextSharp.text.pdf.BaseFont.IDENTITY_H, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);iTextSharp.text.pdf.PdfContentByte pb=Writer.DirectContent;pb.BeginText();pb.SetColorFill(iTextSharp.text.BaseColor.WHITE);pb.SetFontAndSize(bfChinese,10);pb.ShowTextAligned(iTextSharp.text.pdf.PdfContentByte.ALIGN_LEFT, keyword, iTextSharp.text.PageSize.A4.Width- 150, 50, 0);pb.EndText();}document.Close();}}  }

View Code

转载于:https://www.cnblogs.com/love201314/p/10057072.html

倒计时 限制次数记录 公共操作/验证的静态类相关推荐

  1. nonebot2聊天机器人插件5:加群退群通报与退群次数记录join_and_leave

    nonebot2聊天机器人插件5:加群退群通报与退群次数记录join_and_leave 1. 插件用途 2. 目录结构 3. 实现难点与解决方案 3.1 读取加群退群信息 3.2 数据库操作 4. ...

  2. linux系统监控:记录用户操作轨迹,谁动过服务器

    1.前言 我们在实际工作当中,都碰到过误操作.误删除.误修改过配置文件等等事件.对于没有堡垒机的公司来说,要在linux系统上深究到底谁做过配置文件的修改.做过误删除是很头疼的事情,特别是遇到删库跑路 ...

  3. centos6配置日志外发_CentOS6下记录后台操作日志的两种方式

    CentOS6下记录后台操作日志的两种方式 平时为了记录登录CentOS Linux系统的操作命令,需要将操作日志记录下来,下面介绍两种方式 1.利用script以及scriptreplay工具 sc ...

  4. spring boot项目怎么记录用户操作行为和登录时间_6 个 Github 项目拿下 Spring Boot

    经常浏览技术社区.技术公众号的读者会有一个感受,那么就是 Spring Boot 相关的文章和相关咨询越来越多.包括小逛和技术公众号的博主交流,他们也发现推送 Spring Boot 相关的文章阅读量 ...

  5. (第六天)学习Python的元组,字典,集合,公共操作

    目录 7.1.1 元组的介绍 7.1.2定义元组 7.1.3 元组的常见操作 7.2.1 字典的介绍 7.2.2 创建字典 7.2.3 字典的常见操作 7.2.3.1增2 7.2.3.2 删 7.2. ...

  6. week7 day3 记录相关操作之单表查询

    week7 day3 记录相关操作之单表查询 1.1 单表查询的用法 1.2 关键字的执行优先级(重点) 1.3 简单查询 1.4 WHERE约束 1.5 分组查询GROUP BY 1.6 HAVIN ...

  7. Util应用程序框架公共操作类(八):Lambda表达式公共操作类(二)

    前面介绍了查询的基础扩展,下面准备给大家介绍一些有用的查询封装手法,比如对日期范围查询,数值范围查询的封装等,为了支持这些功能,需要增强公共操作类. Lambda表达式公共操作类,我在前面已经简单介绍 ...

  8. og-bin=mysql-bin_init_connect + binlog 记录 mysql 操作日志

    init_connect + binlog 记录 mysql 操作日志 简介 mysql 的 init_connect 变量是每个客户端连上数据库服务器时执行的一组数据,这组数据可以是一个或者多个sq ...

  9. MYSQL触发器记录用户操作的命令

    假如有一张重要的表btb,需要几个管理员来管理 管理员:ma1@localhost.ma2@localhost.ma3@localhost 要求给表btb创建触发器: trigger触发器需求: 1. ...

最新文章

  1. mysql ceill_MYSQL常用函数
  2. 【连载】物联网全栈教程-从云端到设备(十三)---安装单片机编译环境
  3. Java 理论与实践: 垃圾收集简史
  4. 3DSlicer9:FAQ-3
  5. 如何创建 Angular library 并在生产环境中消费
  6. 属性类:Properties
  7. 百度云 网盘无法下载,错误提示:MSXML组件版本太低
  8. poj 2263 最短路变形——最小边的最大值
  9. 天籁obd接口针脚定义_关于手机MicroUSB接口数据线,这里有最详细解说
  10. PHP之JWT接口鉴权(二) 自定义错误异常
  11. Java简单代码-用*号拼三角形
  12. VirtualBox安装Ubuntu教程
  13. 图像彩色化方法(基于颜色传递、颜色扩展)
  14. U盘安装win8.1
  15. SQL学习之now()函数
  16. Java-断点续传(分片上传)
  17. 赛扬处理器_英特尔发布11代奔腾、赛扬处理器 均支持AVX指令集
  18. 图像去模糊算法 deblur
  19. IS620F PN博途组态TO工艺对象,讨论汇川IS620F 替代西门子V90 PN的可行性
  20. 编写高性能JavaScript

热门文章

  1. Linux从入门到秃头
  2. 6. 【三态门】 74LS244 + 【锁存器】 74LS273
  3. 问题 A: 相约HNUST
  4. Orcle 12c DG 新特性---Far Sync
  5. JAvA傲剑狂刀冰火两重天攻略,《傲剑狂刀-冰火两重天》三大系统攻略
  6. USB连不上电脑,出现Unknown Device问题
  7. 计算机打字大赛策划书,打字比赛策划书
  8. python如何分割年月日_将日期拆分为年、月和日,分隔符不一致
  9. 分享实录 | 阿里巴巴代码缺陷检测探索与实践
  10. view.setAlpha(float alpha)与view.getBackground().setAlpha(int alpha)的区别