using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace E656.Utility
{
public static class Utils
{
private static char[] charval;
private static Regex reip;
private static Regex rehex;
private static Regex remail;
private static Regex remobile;
private static Regex rech;
private static Regex rehasimage;
private static Regex reimage;
private static Regex rehtml;
#region IsNumberList
public static bool IsNumberList(string str)
{
return IsNumberList(str, ',');
}
public static bool IsNumber(string str)
{
reip = new Regex(@"^(([1-9]+[0-9]*.{1}[0-9]+)|([0].{1}[1-9]+[0-9]*)|([1-9][0-9]*)|([0][.][0-9]+[1-9]*))$", RegexOptions.Compiled);
return reip.IsMatch(str);
}
public static bool IsNumberList(string str, char separator)
{
if (str == null)
{
return false;
}
int length = str.Length;
if (length == 0)
{
return false;
}
if (!char.IsNumber(str[0]) || !char.IsNumber(str[length - 1]))
{
return false;
}
length--;
for (int i = 1; i < length; i++)
{
if (separator == str[i])
{
if (!char.IsNumber(str[i - 1]) || !char.IsNumber(str[i + 1]))
{
return false;
}
}
else if (!char.IsNumber(str[i]))
{
return false;
}
}
return true;
}
#endregion
#region IsIP
public static bool IsIP(string s)
{
if (reip == null) reip = new Regex(@"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:\.\d{1,3}\.\d{1,3})?$", RegexOptions.Compiled);
return reip.IsMatch(s);
}
#endregion
#region IsHex
public static bool IsHex(string s)
{
if (rehex == null) rehex = new Regex("^[0-9A-Za-z]*$", RegexOptions.Compiled);
return rehex.IsMatch(s);
}
#endregion
#region IsMail
public static bool IsMail(string s)
{
if (remail == null) remail = new Regex("^[a-z](?:[a-z0-9]*[-_]?[a-z0-9]+)*@(?:[a-z0-9]*[-_]?[a-z0-9]+)+\\.[a-z]{2,3}(?:\\.[a-z]{2})?$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
return remail.IsMatch(s);
}
#endregion
#region IsMobile
public static bool IsMobile(string s)
{
if (remobile == null) remobile = new Regex("^1[358][0-9]{9}$", RegexOptions.Compiled);
return remobile.IsMatch(s);
}
#endregion
#region IsChinese
public static bool IsChinese(string s)
{
if (rech == null) rech = new Regex("^[\u4e00-\u9fa5]{2,4}$", RegexOptions.Compiled);
return rech.IsMatch(s);
}
#endregion
#region HasImg
public static bool HasImg(string input)
{
if (rehasimage == null) rehasimage = new Regex(@"<img [^>]*src=\""[^\""]+\""[^>]*>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
return rehasimage.IsMatch(input);
}
#endregion
#region GetImgUrl
public static string GetImgUrl(string input)
{
if (reimage == null) reimage = new Regex(@"<img [^>]*src=\""([^\""]+)\""[^>]*>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
return reimage.Match(input).Groups[1].Value;
}
#endregion
#region GetImgUrlList
public static string[] GetImgUrlList(string input)
{
if (reimage == null) reimage = new Regex(@"<img [^>]*src=\""([^\""]+)\""[^>]*>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
MatchCollection mc = reimage.Matches(input);
int j = mc.Count;
string[] ret = new string[j];
for (int i = 0; i < j; i++)
{
ret[i] = mc[i].Groups[1].Value;
}
return ret;
}
#endregion
#region GetBool
public static bool GetBool(string id)
{
bool newid;
if (id == null)
{
return false;
}
if ((id.Length == 1) && (id[0] == '1'))
{
return true;
}
bool.TryParse(id, out newid);
return newid;
}
#endregion
#region GetInt
public static int GetInt(string id)
{
int newid;
int.TryParse(id, out newid);
return newid;
}
public static int GetInt(string id, int exceptionId)
{
int newid;
if (!int.TryParse(id, out newid))
{
newid = exceptionId;
}
return newid;
}
#endregion
#region GetLong
public static long GetLong(string id)
{
long newid;
long.TryParse(id, out newid);
return newid;
}
public static long GetLong(string id, long exceptionId)
{
long newid;
if (!long.TryParse(id, out newid))
{
newid = exceptionId;
}
return newid;
}
#endregion
#region GetDouble
public static double GetDouble(string id)
{
double newid;
double.TryParse(id, out newid);
return newid;
}
public static double GetDouble(string id, double exceptionId)
{
double newid;
if (!double.TryParse(id, out newid))
{
newid = exceptionId;
}
return newid;
}
#endregion
#region GetDecimal
public static decimal GetDecimal(string id)
{
decimal newid;
decimal.TryParse(id, out newid);
return newid;
}
public static decimal GetDecimal(string id, decimal exceptionId)
{
decimal newid;
if (!decimal.TryParse(id, out newid))
{
newid = exceptionId;
}
return newid;
}
#endregion
#region GetString
public static string GetString(string input)
{
if (input == null)
return String.Empty;
else
return input;
}
public static string GetString(object input)
{
if (input == null)
return String.Empty;
else
return input.ToString();
}
#endregion
#region GetDateTime
public static DateTime GetDateTime(string dt)
{
DateTime newdt;
DateTime.TryParse(dt, out newdt);
return newdt;
}
public static DateTime GetDateTime(string dt, DateTime exceptiondt)
{
DateTime newdt;
if (!DateTime.TryParse(dt, out newdt))
{
newdt = exceptiondt;
}
return newdt;
}
#endregion
#region Left
public static string Left(string input, int need)
{
return Left(input, need, "...");
}
public static string Left(string input, int need, string end)
{
char ch;
if (input == null) return string.Empty;
int length = input.Length;
if (length < (need / 2))
{
return input;
}
int ti = 0;
int i = 0;
for (; i < length; i++)
{
if (ti == need)
{
break;
}
ch = input[i];
if (Convert.ToUInt16(ch) > 0xff)
{
ti += 2;
if (ti > need)
{
ti -= 2;
break;
}
}
else
{
ti++;
}
}
string str = input.Substring(0, i);
int endlen = Len(end);
if (((endlen <= 0) || (i >= length)) || (need <= endlen))
{
return str;
}
need -= endlen;
while (i >= 0)
{
if (ti <= need)
{
break;
}
ch = input[i];
ti -= Convert.ToUInt16(ch) > 0xff ? 2 : 1;
i--;
}
return (input.Substring(0, i) + end);
}
#endregion
#region Len
public static int Len(string input)
{
if (String.IsNullOrEmpty(input))
{
return 0;
}
int nLength = input.Length;
int i = 0;
int j = input.Length;
while (i < j)
{
if (Convert.ToUInt16(input[i]) > 0xff)
{
nLength++;
}
i++;
}
return nLength;
}
#endregion
#region RemoveHTML
public static string RemoveHTML(object input)
{
return RemoveHTML(GetString(input));
}
public static string RemoveHTML(string input)
{
if (input == null) throw new ArgumentNullException("input");
if (rehtml == null) rehtml = new Regex("<[^>]*>|\\s| ", RegexOptions.Compiled);
return rehtml.Replace(input, string.Empty);
}
#endregion
#region 获取散列值
public static string GenerateSalt()
{
return GenerateSalt(0x10);
}
public static string GenerateSalt(int len)
{
byte[] data = new byte[len];
new RNGCryptoServiceProvider().GetBytes(data);
return Convert.ToBase64String(data);
}
#endregion
#region 获取随机种子
public static int GenerateSeed()
{
byte[] bytes = new byte[4];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
#endregion
#region MD5
public static string MD5(string password)
{
if (password == null) password = string.Empty;
byte[] bytes = Encoding.UTF8.GetBytes(password);
using (MD5 md5 = new MD5CryptoServiceProvider())
{
return ByteArrayToHexString(md5.ComputeHash(bytes), 0);
}
}
#endregion
#region ByteArrayToHexString
public unsafe static string ByteArrayToHexString(byte[] buf, int iLen)
{
char[] chArray = charval;
if (chArray == null)
{
chArray = new char[0x10];
int length = chArray.Length;
while (--length >= 0)
{
if (length < 10)
{
chArray[length] = (char)(0x30 + length);
}
else
{
chArray[length] = (char)(0x61 + (length - 10));
}
}
charval = chArray;
}
if (buf == null)
{
return null;
}
if (iLen == 0)
{
iLen = buf.Length;
}
char[] chArray2 = new char[iLen * 2L];
fixed (char* chRef = chArray2)
{
fixed (char* chRef2 = chArray)
{
fixed (byte* numRef = buf)
{
char* chPtr = chRef;
for (byte* numPtr = numRef; --iLen >= 0; numPtr++)
{
chPtr++[0] = chRef2[(numPtr[0] & 240) >> 4];
chPtr++[0] = chRef2[numPtr[0] & 15];
}
}
}
}
return new string(chArray2);
}
#endregion
#region 混合散列+MD5
public static string EncodePassword(string pass, string salt)
{
return EncodePassword(Encoding.Unicode.GetBytes(pass), salt);
}
public static string EncodePassword(byte[] bytes, string salt)
{
byte[] src = Convert.FromBase64String(salt);
int srcLen = src.Length;
byte[] dst = new byte[srcLen + bytes.Length + 1];
Buffer.BlockCopy(src, 0, dst, 0, srcLen);
dst[srcLen] = 0x39;
Buffer.BlockCopy(bytes, 0, dst, srcLen + 1, bytes.Length);
using (MD5 md5 = new MD5CryptoServiceProvider())
{
return Convert.ToBase64String(md5.ComputeHash(dst));
}
}
#endregion
#region GenerateFixedThumbnail
/// <summary>
/// 创建固定大小的缩略图,图片按比例缩放到设定范围内,空白区域透明。
/// </summary>
/// <param name="input">图片流</param>
/// <param name="width">宽度</param>
/// <param name="height">高度</param>
/// <param name="filename">保存路径(GIF格式)</param>
public static void GenerateFixedThumbnail(Stream input, int width, int height, string filename)
{
if (input == null) throw new ArgumentNullException("input");
if (filename == null) throw new ArgumentNullException("filename");
Image img = null;
Bitmap bmp = null;
Graphics g = null;
try
{
img = Image.FromStream(input);
int s_Width = img.Width;
int s_Height = img.Height;
int d_Width;
int d_Height;
int X;
int Y;
if (height * s_Width > width * s_Height)
{
d_Width = width;
d_Height = d_Width * s_Height / s_Width;
X = 0;
Y = (height - d_Height) / 2;
}
else
{
d_Height = height;
d_Width = d_Height * s_Width / s_Height;
X = (width - d_Width) / 2;
Y = 0;
}
bmp = new Bitmap(width, height);
g = Graphics.FromImage(bmp);
g.Clear(Color.Transparent);
g.InterpolationMode = InterpolationMode.High;
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawImage(img, new Rectangle(X, Y, d_Width, d_Height), new Rectangle(0, 0, s_Width, s_Height), GraphicsUnit.Pixel);
bmp.Save(filename, ImageFormat.Gif);
}
finally
{
if (img != null) img.Dispose();
if (bmp != null) bmp.Dispose();
if (g != null) g.Dispose();
}
}
#endregion
#region GenerateTangentThumbnail
/// <summary>
/// 按比例缩放或放大图片到设定范围内,返回缩放后的图片。
/// </summary>
/// <param name="input">图片流</param>
/// <param name="width">宽度</param>
/// <param name="height">高度</param>
/// <param name="filename">保存路径(JPG格式)</param>
public static void GenerateTangentThumbnail(Stream input, int width, int height, string filename)
{
if (input == null) throw new ArgumentNullException("input");
if (filename == null) throw new ArgumentNullException("filename");
Image img = null;
Bitmap bmp = null;
Graphics g = null;
try
{
img = Image.FromStream(input);
int s_Width = img.Width;
int s_Height = img.Height;
int d_Width;
int d_Height;
if (height * s_Width > width * s_Height)
{
d_Width = width;
d_Height = d_Width * s_Height / s_Width;
}
else
{
d_Height = height;
d_Width = d_Height * s_Width / s_Height;
}
bmp = new Bitmap(d_Width, d_Height);
g = Graphics.FromImage(bmp);
g.Clear(Color.Transparent);
g.InterpolationMode = InterpolationMode.High;
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawImage(img, new Rectangle(0, 0, d_Width, d_Height), new Rectangle(0, 0, s_Width, s_Height), GraphicsUnit.Pixel);
bmp.Save(filename, ImageFormat.Jpeg);
}
finally
{
if (img != null) img.Dispose();
if (bmp != null) bmp.Dispose();
if (g != null) g.Dispose();
}
}
#endregion
#region GenerateScaleThumbnail
/// <summary>
/// 按比例缩放图片到设定范围内,返回缩放后的图片。
/// </summary>
/// <param name="input">图片流</param>
/// <param name="width">宽度</param>
/// <param name="height">高度</param>
/// <param name="filename">保存路径(JPG格式)</param>
public static void GenerateScaleThumbnail(Stream input, int width, int height, string filename)
{
if (input == null) throw new ArgumentNullException("input");
if (filename == null) throw new ArgumentNullException("filename");
Image img = null;
Bitmap bmp = null;
Graphics g = null;
try
{
img = Image.FromStream(input);
int s_Width = img.Width;
int s_Height = img.Height;
int d_Width;
int d_Height;
if (s_Width < width && s_Height < height)
{
d_Width = s_Width;
d_Height = s_Height;
}
else if (height * s_Width > width * s_Height)
{
d_Width = width;
d_Height = d_Width * s_Height / s_Width;
}
else
{
d_Height = height;
d_Width = d_Height * s_Width / s_Height;
}
bmp = new Bitmap(d_Width, d_Height);
g = Graphics.FromImage(bmp);
g.Clear(Color.Transparent);
g.InterpolationMode = InterpolationMode.High;
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawImage(img, new Rectangle(0, 0, d_Width, d_Height), new Rectangle(0, 0, s_Width, s_Height), GraphicsUnit.Pixel);
bmp.Save(filename, ImageFormat.Jpeg);
}
finally
{
if (img != null) img.Dispose();
if (bmp != null) bmp.Dispose();
if (g != null) g.Dispose();
}
}
#endregion
#region DES加密字符串
/// <summary>
/// DES加密方法
/// </summary>
/// <param name="plain">明文</param>
/// <returns>密文</returns>
public static String EncryptDES(string plain)
{
byte[] key = Encoding.ASCII.GetBytes("Oh!MyGod");
byte[] iv = Encoding.ASCII.GetBytes("e656#%&@");
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, iv), CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cs);
sw.Write(plain);
sw.Flush();
cs.FlushFinalBlock();
ms.Flush();
return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
}
#endregion
#region 验证电话号码
public static bool IsTelephone(string str)
{
return System.Text.RegularExpressions.Regex.IsMatch(str, "^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$");
}
#endregion
#region 验证身份证号码
public static bool IsCardID(string str)
{
return System.Text.RegularExpressions.Regex.IsMatch(str, @"^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$");
}
#endregion
}
}