倒计时 限制次数记录 公共操作/验证的静态类
限制次数记录
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("服务器错误"); } } }) } }
倒计时:
//倒计时 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 ); } }
公共操作/验证的静态类
/// <summary> /// 公共操作/验证的静态类 /// </summary> public static partial class Util { #region 验证格式正确性的方法 #region 验证是否是手机号码格式 /// <summary> /// 验证是否是手机号码格式 /// (可以验证以 13、14、15、17、18 开头的手机号格式) /// </summary> /// <param name="mobile">需要验证的手机号码</param> /// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns> public static bool IsMobile(string mobile) { return Regex.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(string phone) { return Regex.IsMatch(phone, RegularString.Phone); } #endregion #region 验证是否是数值类型 /// <summary> /// 验证是否是数值类型 /// </summary> /// <param name="num">需要验证的数值字符串</param> /// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns> public static bool IsDecimal(string num) { decimal res; if (decimal.TryParse(num, out res)) { return true; } return false; } #endregion #region 验证是否是数字字符串 /// <summary> /// 验证是否是数字字符串(不带正、负号) /// </summary> /// <param name="num">要验证的数字字符串</param> /// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns> public static bool IsNumber(string num) { if (string.IsNullOrWhiteSpace(num)) { return false; } return Regex.IsMatch(num, RegularString.Number); } #endregion #region 验证纯字母字符串 /// <summary> /// 验证纯字母字符串 /// </summary> /// <param name="str">要验证的字符串</param> /// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns> public static bool IsLetter(string str) { return Regex.IsMatch(str, RegularString.Letter); } #endregion #region 验证是否是带正、负号的数字字符串 /// <summary> /// 验证是否是带正、负号的数字字符串 /// </summary> /// <param name="num">要验证的字符串</param> /// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns> public static bool IsNumberSign(string num) { return Regex.IsMatch(num, RegularString.NumberSign); } #endregion #region 验证是否是Email地址格式 /// <summary> /// 验证是否是Email地址格式 /// </summary> /// <param name="email">输入需要验证的email地址</param> /// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns> public static bool IsEmail(string email) { return Regex.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(string ip) { return Regex.IsMatch(ip, RegularString.IP); } #endregion #region 验证是否是邮政编码 /// <summary> /// 验证是否是邮政编码 /// 可以验证6位数字格式的中国邮政编码 /// </summary> /// <param name="source"></param> /// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns> public static bool IsPostCode(string postCode) { //return Regex.IsMatch(postCode, @"^[0-9A-Za-z]{1,10}$", RegexOptions.IgnoreCase); return Regex.IsMatch(postCode, RegularString.PostCode); } #endregion #region 验证是否是字母、数字、"_" /// <summary> /// 验证是否是字母、数字、"_" /// </summary> /// <param name="str">需要验证的字符串</param> /// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns> public static bool IsLetterNumber(string str) { return Regex.IsMatch(str, RegularString.LetterNumber); } #endregion #region 验证是否是汉字 /// <summary> /// 验证是否是汉字 /// </summary> /// <param name="str">需要验证的字符串</param> /// <returns>返回bool类型,true表示验证通过,false表示验证未通过</returns> public static bool IsChinese(string str) { return Regex.IsMatch(str, RegularString.Chinese); } #endregion #region 验证是否是正确的日期格式 /// <summary> /// 验证是否是正确的日期格式 /// </summary> /// <param name="str">要检查的字串</param> /// <returns>bool</returns> public static bool IsDateTime(string str) { DateTime dt; if (DateTime.TryParse(str, out dt)) { return true; } return false; } #endregion #region 验证文件扩展名是否图片文件 /// <summary> /// 验证文件扩展名是否图片文件 /// 可以验证后缀名为 jpg、jpeg、gif、png 格式的文件 /// </summary> /// <param name="fileName">需要验证的文件名</param> /// <returns></returns> public static bool IsImage(string fileName) { return Regex.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(string cardNum) { 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 = new DateTime(); if (cardNum.Length == 18) { birth = cardNum.Substring(6, 8).Insert(6, "-").Insert(4, "-"); if (DateTime.TryParse(birth, out birthTime)) { // 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, out y); 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, out birthTime)) { flag = true; } } } } } return flag; } #endregion #region 根据身份证号码获取出生日期字符串 /// <summary> /// 根据身份证号码获取出生日期字符串 /// </summary> /// <param name="cardNum">身份证号码</param> /// <returns>返回出生日期字符串,""表示身份证号码格式有误</returns> public static string GetBirthFromIdCard(string cardNum) { 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, "-"); } } return result; } #endregion #region 身份证号格式化(隐藏出生年月日) /// <summary> /// 身份证号格式化(隐藏出生年月日) /// </summary> /// <param name="IdCard">身份证号码</param> /// <returns></returns> public static string IdCardFormatHideBirth(string IdCard) { 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); } return strIdCard; } #endregion #region 根据身份证号码获取性别 /// <summary> /// 根据身份证号码获取性别 /// </summary> /// <param name="cardNum">身份证号码</param> /// <returns>返回代表性别的代码,"m"表示男性, "w"表示女性,""表示身份证格式有误</returns> public static string GetSexFromIdCard(string cardNum) { 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, out sex); if (sex == 0) { result = "w"; } else { result = "m"; } } return result; } #endregion #region 根据身份证号码获取年龄 /// <summary> /// 根据身份证号获取实际年龄 /// </summary> /// <param name="idcard">身份证号</param> /// <returns>实际年龄</returns> public static int GetAgeFromIdCard(string idcard) { 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--; return age; } /// <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 string GetGuid() { return Guid.NewGuid().ToString().ToUpper(); } #endregion #region 生成n位随机验证码 /// <summary> /// 生成n位随机验证码算法 /// </summary> /// <param name="n">生成随机验证的位数</param> /// <returns>返回生成的验证码</returns> public static string RandomCode(int n, bool OnlyNumber = false) { int number; char code; string StrCode = String.Empty; Random random = new Random(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)); else code = (char)('A' + (char)(number % 26)); StrCode += code.ToString(); } else { number = random.Next(0, 9); StrCode += number.ToString(); } } return StrCode; } /// <summary> /// 生成随机码 /// </summary> /// <param name="min"></param> /// <param name="max"></param> /// <returns></returns> public static int rand(int min, int max) { Random rd = new Random(); return (int)((max - min + 1) * rd.NextDouble() + min); } #endregion #region 计算指定时间与当前时间的间隔 /// <summary> /// 计算指定时间与当前时间的间隔 /// </summary> /// <param name="dt">指定时间</param> /// <returns>返回类似“5秒前”、“5天前”、“5周前”的格式</returns> public static string DateToSpan(DateTime dt) { if (dt != null) { TimeSpan timeSpan = DateTime.Now - dt; if (timeSpan.TotalDays > 60) { return dt.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); } return result; } #endregion #region 组织Alert字符串,不包括<scripts>标签 /// <summary> /// 组织Alert字符串,不包括 scripts 标签 /// </summary> /// <param name="msg">要显示的消息内容</param> /// <returns>返回结果字符串</returns> public static string Alert(string msg) { 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, string redirectUrl) { 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(string msg) { 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, string redirectUrl) { 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, string concelUrl) { string msg = "数据已经提交成功!\\n继续提交数据?"; return Confirm(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, string concelUrl) { //<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(string strHtml) { 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 = new Regex(aryReg[i], RegexOptions.IgnoreCase); result = regex.Replace(result, aryRep[i]); } result = result.Replace("<", "").Replace(">", "").Replace("\r", ""); } return result; } #endregion #region 获取文件的扩展名 /// <summary> /// 获取文件的扩展名,格式为".txt"、".gif"、".docx"等 /// </summary> /// <param name="fileName">文件名称(可以包含路径)</param> /// <returns>返回扩展名,格式为".txt"、".gif"、".docx"等</returns> public static string GetFileExt(string fileName) { string result = string.Empty; if (!string.IsNullOrEmpty(fileName)) { int index = fileName.LastIndexOf('.'); if (index > 0) { result = fileName.Substring(index); } } return result; } #endregion #region 根据文件名判断文件类型 /// <summary> /// 判断文件是否是图片 /// </summary> /// <param name="FileName"></param> /// <returns></returns> public static bool IsImageAndPdf(string FileName) { 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(string FileName) { 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(string fileName) { string result = fileName; if (!string.IsNullOrEmpty(fileName)) { int index = fileName.LastIndexOf('\\'); if (index > 0) { result = fileName.Substring(index + 1); } } return result; } #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 = new DirectoryInfo(folderFullName); if (searchPattern == null) { return theFolder.GetFiles(); } return theFolder.GetFiles(searchPattern); } #endregion #region 获取文件 哈希码 public static string GetFileHashMD5(string fileName) { using (HashAlgorithm hashMD5 = new MD5CryptoServiceProvider()) { using (Stream file = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { byte[] hash = hashMD5.ComputeHash(file); return BitConverter.ToString(hash).Replace("-", string.Empty); } } } public static string GetFileHashMD5AndLength(string fileName, out long fileLength) { using (HashAlgorithm hashMD5 = new MD5CryptoServiceProvider()) { using (Stream file = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { byte[] hash = hashMD5.ComputeHash(file); fileLength = file.Length; return BitConverter.ToString(hash).Replace("-", string.Empty); } } } public static string GetFileHashSHA1(string fileName) { using (HashAlgorithm hashSHA1 = new SHA1Managed()) { using (Stream file = new FileStream(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(string str) { string result = string.Empty; if (!string.IsNullOrEmpty(str)) { //替换回车换行,因为换行有几种标记,所以依次替换 result = str.Replace("\r\n", "<br />").Replace("\r", "<br />").Replace("\n", "<br />").Replace(" ", " "); } return result; } #endregion #region 获取字符串前面部分 /// <summary> /// 获取字符串前面部分 /// (此方法有bug) /// </summary> /// <param name="str">需要截取的原字符串</param> /// <param name="len">需要截取的长度</param> /// <returns>返回截取后的字符串</returns> public static string GetPreString(string str, int len) { string result = string.Empty; if (!string.IsNullOrEmpty(str)) { char[] arrChar = str.ToCharArray(); if (arrChar.Length <= len) { result = str; } else { StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { sb.Append(arrChar[i]); } sb.Append("..."); result = sb.ToString(); } } return result; } /// <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, string suffix) { string tempStr = inputStr.Substring(0, (inputStr.Length < length) ? inputStr.Length : length); if (Regex.Replace(tempStr, "[\u4e00-\u9fa5]", "aa", RegexOptions.IgnoreCase).Length <= length) { return tempStr; } 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; } } return suffix; } #endregion #region 获取字符串长度(中文算两个字符) /// <summary> /// 获取字符串长度(中文算两个字符) /// </summary> /// <param name="str"></param> /// <returns></returns> public static int ChineseLength(string str) { if (string.IsNullOrEmpty(str)) return 0; int lenTotal = str.Length; int asc; 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; } return lenTotal; } #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, int length) { 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; } return str.Substring(startIndex, length); } #endregion #region DecodeBase64 /// <summary> /// 主要用于为字段"MerPriv"解密 /// </summary> /// <param name="strEncStr"></param> /// <returns></returns> public static string DecodeBase64(string strEncStr) { string reDecStr = string.Empty; byte[] bytes = Convert.FromBase64String(strEncStr); try { reDecStr = Encoding.UTF8.GetString(bytes); } catch (Exception ex) { throw ex; } return reDecStr; } #endregion #region 类型与Byte数组转换 /// <summary> /// 序列化一个对象 /// </summary> /// <param name="entity"></param> /// <returns></returns> public static byte[] SerializeBinary(object entity) { if (entity == null) { return null; } try { MemoryStream ms = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, entity); return ms.ToArray(); } catch (Exception ex) { throw ex; } } public static T DeserializeBinary<T>(byte[] bytes) { if (bytes == null) { return default(T); } try { MemoryStream ms = new MemoryStream(bytes); BinaryFormatter bf = new BinaryFormatter(); return (T)bf.Deserialize(ms); } catch { return default(T); } } #endregion #region 读取文件到字节数组中 /// <summary> /// 读取文件到字节数组中 /// </summary> /// <param name="path">文件路径</param> /// <returns></returns> public static byte[] ReadFileTobytes(string path) { byte[] bts = new byte[0]; try { FileStream fs = new FileStream(path, FileMode.Open); long size = fs.Length; bts = new byte[size]; fs.Read(bts, 0, bts.Length); fs.Close(); return bts; } catch (Exception) { return bts; } } public static sbyte[] ReadFileToSbytes(string path) { FileStream fs = new FileStream(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]); } return sbyteArray; } #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]); } return sbyteArray; } #endregion #region 去除字符串中的空格 /// <summary> /// 去除字符串中的空格 /// </summary> /// <param name="text"></param> /// <returns></returns> public static string TrimSpace(string text) { 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 in source) { if (seenKeys.Add(keySelector(element))) { yield return element; } } } #endregion #endregion #region 简单封装部分 #region 实例化SMTP服务 /// <summary> /// 实例化SMTP服务 /// </summary> /// <returns></returns> public static SMTP 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 new SMTP(userName, smtpServer, userName, password); } #endregion #region 根据Email地址获取Email的登录地址 /// <summary> /// 根据Email地址获取Email的登录地址 /// </summary> /// <param name="mailAddr">Email地址</param> /// <returns></returns> public static string GetMailLogin(string email) { 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; } } return mailLogin; } #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)) return defVal; int result; if (int.TryParse(val, out result)) { return result; } else { return defVal; } } /// <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)) return defVal; long result; if (long.TryParse(val, out result)) { return result; } else { return defVal; } } /// <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)) return defVal; double result; if (double.TryParse(val, out result)) { return result; } else { return defVal; } } public static string DoubleToStr(double? val, string format = "f2") { if (val == null) return string.Empty; return val.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)) return defVal; decimal result; if (decimal.TryParse(val, out result)) { return result; } else { return defVal; } } public static string DecimalToStr(decimal? val, string format = "f2") { if (val == null) return string.Empty; return val.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)) return defVal; DateTime result; if (DateTime.TryParse(val, out result)) { return result; } else { return defVal; } } public static DateTime? StrToDateTimeByyyyyMMdd(string val, DateTime? defVal) { if (string.IsNullOrWhiteSpace(val)) return defVal; DateTime result; if (DateTime.TryParseExact(val, "yyyyMMdd HH:mm:ss", null, System.Globalization.DateTimeStyles.None, out result)) { return result; } else { return defVal; } } public static DateTime? StrToDateTimeBy_yyyyMMdd(string val) { 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 { } return dt; } public static string DateTimeToStr(DateTime? val, string format = "yyyy-MM-dd") { if (null == val) return string.Empty; return val.Value.ToString(format); } public static string DateTimeToStr(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, object toObject) { PropertyInfo[] properties = fromObject.GetType().GetProperties(); Type newType = toObject.GetType(); foreach (PropertyInfo pInfo in properties) { 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) { string m_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) //数量 return m_8; else return m_9; } #endregion #region 日期转中文 /// <summary> /// 日期转中文 /// </summary> /// <param name="strDate">日期</param> /// <returns></returns> public static string GetChineseDate(string strDate) { char[] strChinese = new char[] { '〇','一','二','三','四','五','六','七','八','九','十' }; StringBuilder result = new StringBuilder(); //// 依据正则表达式判断参数是否正确 //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 new ArgumentException(); } return result.ToString(); } #endregion #region 程序当前路径 public static string BaseDirectory { 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, string strDefaultValue) { string strParameterValue = HttpContext.Current.Request.Form[strParameterName] == null ? strDefaultValue : HttpUtility.UrlDecode(HttpContext.Current.Request.Form[strParameterName], Encoding.UTF8); return strParameterValue; } /// <summary> /// 不同资金平台 对应 不同的合同名称 /// </summary> /// <param name="FundGuid">资金平台GUID</param> /// <returns></returns> public static string GetContactName(string FundGuid) { string name = ""; switch (FundGuid) { case ConstValue.FundType_1: case ConstValue.FundType_2: case ConstValue.FundType_5: case ConstValue.FundType_6: case ConstValue.FundType_7: case ConstValue.FundType_8: case ConstValue.FundType_9: case ConstValue.FundType_10: case ConstValue.FundType_14: case ConstValue.FundType_15: case ConstValue.FundType_24: name = "小额借款服务合同"; break; case ConstValue.FundType_3: name = "委托贷款合同"; break; case ConstValue.FundType_4: case ConstValue.FundType_11: case ConstValue.FundType_13: name = "信托借款合同"; break; case ConstValue.FundType_12: name = "杭州银行股份有限公司个人小额代理贷款借款合同"; break; case ConstValue.FundType_20: case ConstValue.FundType_JuYouCai: name = "小额借款咨询服务合同"; break; default: name = "小额借款服务合同"; break; } return name; } #endregion #region 清理手机及座机号码格式 /// <summary> /// 清理手机及座机号码格式,去掉 - 、17909前缀等 /// </summary> /// <param name="phoneNo"></param> /// <returns></returns> public static string ClearPhoneNo(string phoneNo) { 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("-", ""); return phoneNo; } #endregion #region 判断手机号是属于哪个运营商的 /// <summary> /// 判断手机号是属于哪个运营商的 /// </summary> /// <param name="phoneNo"></param> /// <returns></returns> public static string CommunicationsOperatorName(string phoneNo) { 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; } return value; } #endregion /// <summary> /// 根据枚举获取对应属性描述 /// </summary> /// <param name="enumValue"></param> /// <returns></returns> public static string GetEnumDescription(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) return str; System.ComponentModel.DescriptionAttribute da = (System.ComponentModel.DescriptionAttribute)objs[0]; return da.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, double lat2) { 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; return result; } /// <summary> /// 经纬度转化成弧度 /// </summary> /// <param name="d"></param> /// <returns></returns> private static double Rad(double d) { 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 = 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 = 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); else tmp.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(); throw ex; //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 = 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(); } } public static System.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; else nPercent = nPercentW; //期望的宽度 int destWidth = (int)(sourceWidth * nPercent); //期望的高度 int destHeight = (int)(sourceHeight * nPercent); Bitmap b = new Bitmap(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, string fileName, FileInfo[] files) { int iHeight = 0; ArrayList _alMemo = new ArrayList(); foreach (var item in files) { 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 = new FileStream(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; //MemoryStream MemoryStream ms = null; MemoryStream imgms = null; //Bitmap Bitmap bmp = null; //image System.Drawing.Image img = null; //Graphics Graphics gp = null; try { ms = new MemoryStream(); //if (!string.IsNullOrWhiteSpace(strText)) _height += 100; bmp = new Bitmap(_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 = new Bitmap(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 = new MemoryStream(); img.Save(imgms, img.RawFormat); imgms.Position = 0; tp = new byte[imgms.Length]; imgms.Read(tp, 0, Convert.ToInt32(imgms.Length)); return tp; } catch (Exception ex) { throw new Exception(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 = new MemoryStream(zp); Bitmap btp = new Bitmap(ms); DirectoryInfo dti = new DirectoryInfo(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, string DataType) { if (!string.IsNullOrWhiteSpace(str)) { return str; } string strSpace = Space(); int str_length = 0; if (str != null) { if (str.Length >= length) { str = str.Substring(0, length); return str; } 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); return str; } 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; } } } return str; } /// <summary> /// 返回半角空格 /// </summary> /// <returns></returns> private static string Space() { int AscToInt = Convert.ToInt32("0x20", 16); byte[] bt = new byte[] { (byte)AscToInt }; return Encoding.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 = new FileStream(pdf, FileMode.Create, FileAccess.Write, FileShare.None)) { iTextSharp.text.pdf.PdfWriter Writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, stream); document.Open(); using (var imageStream = new FileStream(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(); } } }