forked from dk96/QuotationMaker
420 lines
13 KiB
C#
420 lines
13 KiB
C#
using System.Security.Cryptography;
|
||
using System.Text;
|
||
using System.Text.RegularExpressions;
|
||
using System.Drawing;
|
||
using System.Drawing.Imaging;
|
||
using System.Drawing.Drawing2D;
|
||
|
||
public static class GlobalClass
|
||
{
|
||
public static IServiceProvider ServiceProvider;
|
||
public static bool isURL(string url)
|
||
{
|
||
return Uri.IsWellFormedUriString(url, UriKind.Absolute);
|
||
}
|
||
|
||
public static string GetIP(this HttpContext context)
|
||
{
|
||
|
||
var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
|
||
if (string.IsNullOrEmpty(ip))
|
||
{
|
||
ip = context.Connection.RemoteIpAddress.ToString();
|
||
}
|
||
return ip;
|
||
}
|
||
|
||
public static string CreateRandomCode(int Number)
|
||
{
|
||
string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
|
||
string[] allCharArray = allChar.Split(',');
|
||
string randomCode = "";
|
||
|
||
Random rand = new Random(Guid.NewGuid().GetHashCode());
|
||
for (int i = 0; i <= Number - 1; i++)
|
||
{
|
||
int t = rand.Next(allCharArray.Length);
|
||
randomCode += allCharArray[t];
|
||
}
|
||
return randomCode;
|
||
}
|
||
|
||
public static string CreateUniRandomCode(int Number)
|
||
{
|
||
string allChar = "2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,M,N,P,Q,R,S,U,V,W,X,Y,Z";
|
||
string[] allCharArray = allChar.Split(',');
|
||
string randomCode = "";
|
||
|
||
Random rand = new Random(Guid.NewGuid().GetHashCode());
|
||
for (int i = 0; i <= Number - 1; i++)
|
||
{
|
||
int t = rand.Next(allCharArray.Length);
|
||
randomCode += allCharArray[t];
|
||
}
|
||
return randomCode;
|
||
}
|
||
|
||
public static string ToMD5(this string str)
|
||
{
|
||
using (var cryptoMD5 = System.Security.Cryptography.MD5.Create())
|
||
{
|
||
//將字串編碼成 UTF8 位元組陣列
|
||
var bytes = Encoding.UTF8.GetBytes(str);
|
||
|
||
//取得雜湊值位元組陣列
|
||
var hash = cryptoMD5.ComputeHash(bytes);
|
||
|
||
//取得 MD5
|
||
var md5 = BitConverter.ToString(hash)
|
||
.Replace("-", String.Empty)
|
||
.ToLower();
|
||
|
||
return md5;
|
||
}
|
||
}
|
||
|
||
public static string Sha256(this string input)
|
||
{
|
||
System.Security.Cryptography.SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider();
|
||
Byte[] ByteString = Encoding.ASCII.GetBytes(input);
|
||
ByteString = sha256.ComputeHash(ByteString);
|
||
string returnString = "";
|
||
foreach (Byte bt in ByteString)
|
||
{
|
||
returnString += bt.ToString("x2");
|
||
}
|
||
return returnString.ToLower();
|
||
}
|
||
/// <summary>
|
||
/// Creates a SHA256 hash of the specified input.
|
||
/// </summary>
|
||
/// <param name="input">The input.</param>
|
||
/// <returns>A hash.</returns>
|
||
public static byte[] Sha256(this byte[] input)
|
||
{
|
||
if (input == null)
|
||
{
|
||
return null;
|
||
}
|
||
using (var sha = SHA256.Create())
|
||
{
|
||
return sha.ComputeHash(input);
|
||
}
|
||
}
|
||
|
||
public static bool isEmail(string email)
|
||
{
|
||
//Email檢查格式
|
||
System.Text.RegularExpressions.Regex EmailExpression = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", RegexOptions.Compiled | RegexOptions.Singleline);
|
||
try
|
||
{
|
||
if (string.IsNullOrEmpty(email))
|
||
{
|
||
return false;
|
||
}
|
||
else
|
||
{
|
||
return EmailExpression.IsMatch(email);
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
//log.Error(ex.Message);
|
||
return false;
|
||
}
|
||
}
|
||
|
||
public static string appsettings(string key)
|
||
{
|
||
var builder = new ConfigurationBuilder()
|
||
.SetBasePath(Directory.GetCurrentDirectory())
|
||
.AddJsonFile("appsettings.json");
|
||
var config = builder.Build();
|
||
return config[key];
|
||
}
|
||
|
||
public static Image embedImage(Image watermark, Image targetImg, int x, int y)
|
||
{
|
||
Image outImg;
|
||
|
||
using (Graphics g = Graphics.FromImage(targetImg))
|
||
{
|
||
g.DrawImage(watermark, new Rectangle(x, y, watermark.Width, watermark.Height));
|
||
outImg = (Image)targetImg.Clone();
|
||
}
|
||
|
||
return outImg;
|
||
}
|
||
|
||
public static Image resizeImage(Image image, int width, int height)
|
||
{
|
||
var destinationRect = new Rectangle(0, 0, width, height);
|
||
var destinationImage = new Bitmap(width, height);
|
||
|
||
destinationImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
|
||
|
||
using (var graphics = Graphics.FromImage(destinationImage))
|
||
{
|
||
graphics.CompositingMode = CompositingMode.SourceCopy;
|
||
graphics.CompositingQuality = CompositingQuality.HighQuality;
|
||
|
||
using (var wrapMode = new ImageAttributes())
|
||
{
|
||
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
|
||
graphics.DrawImage(image, destinationRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
|
||
}
|
||
}
|
||
|
||
return (Image)destinationImage;
|
||
}
|
||
|
||
/// <summary>
|
||
/// base 64字串格式的圖片轉成Image物件
|
||
/// </summary>
|
||
/// <param name="base64String"></param>
|
||
/// <returns></returns>
|
||
public static Image Base64StringToImage(string base64String)
|
||
{
|
||
// Convert base 64 string to byte[]
|
||
byte[] Buffer = Convert.FromBase64String(base64String);
|
||
|
||
byte[] data = null;
|
||
Image oImage = null;
|
||
MemoryStream oMemoryStream = null;
|
||
Bitmap oBitmap = null;
|
||
//建立副本
|
||
data = (byte[])Buffer.Clone();
|
||
try
|
||
{
|
||
oMemoryStream = new MemoryStream(data);
|
||
//設定資料流位置
|
||
oMemoryStream.Position = 0;
|
||
oImage = System.Drawing.Image.FromStream(oMemoryStream);
|
||
//建立副本
|
||
oBitmap = new Bitmap(oImage);
|
||
}
|
||
catch
|
||
{
|
||
throw;
|
||
}
|
||
finally
|
||
{
|
||
oMemoryStream.Close();
|
||
oMemoryStream.Dispose();
|
||
oMemoryStream = null;
|
||
}
|
||
//return oImage;
|
||
return oBitmap;
|
||
}
|
||
|
||
public static string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
|
||
{
|
||
using (MemoryStream ms = new MemoryStream())
|
||
{
|
||
// Convert Image to byte[]
|
||
image.Save(ms, format);
|
||
byte[] imageBytes = ms.ToArray();
|
||
|
||
// Convert byte[] to base 64 string
|
||
string base64String = Convert.ToBase64String(imageBytes);
|
||
return base64String;
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 日期转换为中文大写
|
||
/// </summary>
|
||
public class UpperConvert
|
||
{
|
||
public UpperConvert()
|
||
{
|
||
//
|
||
// TODO: 在此处添加构造函数逻辑
|
||
//
|
||
}
|
||
//把数字转换为大写
|
||
public string numtoUpper(int num)
|
||
{
|
||
String str = num.ToString();
|
||
string rstr = "";
|
||
int n;
|
||
for (int i = 0; i < str.Length; i++)
|
||
{
|
||
n = Convert.ToInt16(str[i].ToString());//char转数字,转换为字符串,再转数字
|
||
switch (n)
|
||
{
|
||
case 0: rstr = rstr + "〇"; break;
|
||
case 1: rstr = rstr + "一"; break;
|
||
case 2: rstr = rstr + "二"; break;
|
||
case 3: rstr = rstr + "三"; break;
|
||
case 4: rstr = rstr + "四"; break;
|
||
case 5: rstr = rstr + "五"; break;
|
||
case 6: rstr = rstr + "六"; break;
|
||
case 7: rstr = rstr + "七"; break;
|
||
case 8: rstr = rstr + "八"; break;
|
||
default: rstr = rstr + "九"; break;
|
||
}
|
||
|
||
}
|
||
return rstr;
|
||
}
|
||
//月转化为大写
|
||
public string monthtoUpper(int month)
|
||
{
|
||
if (month < 10)
|
||
{
|
||
return numtoUpper(month);
|
||
}
|
||
else
|
||
if (month == 10) { return "十"; }
|
||
|
||
else
|
||
{
|
||
return "十" + numtoUpper(month - 10);
|
||
}
|
||
}
|
||
//日转化为大写
|
||
public string daytoUpper(int day)
|
||
{
|
||
if (day < 20)
|
||
{
|
||
return monthtoUpper(day);
|
||
}
|
||
else
|
||
{
|
||
String str = day.ToString();
|
||
if (str[1] == '0')
|
||
{
|
||
return numtoUpper(Convert.ToInt16(str[0].ToString())) + "十";
|
||
}
|
||
else
|
||
{
|
||
return numtoUpper(Convert.ToInt16(str[0].ToString())) + "十"
|
||
+ numtoUpper(Convert.ToInt16(str[1].ToString()));
|
||
}
|
||
}
|
||
}
|
||
//日期转换为大写
|
||
public string dateToUpper(System.DateTime date)
|
||
{
|
||
int year = date.Year;
|
||
int month = date.Month;
|
||
int day = date.Day;
|
||
return numtoUpper(year) + "年" + monthtoUpper(month) + "月" + daytoUpper(day) + "日";
|
||
|
||
}
|
||
}
|
||
|
||
public class ChtNumConverter
|
||
{
|
||
public static string ChtNums = "零壹貳參肆伍陸柒捌玖";
|
||
public static Dictionary<string, long> ChtUnits = new Dictionary<string, long>{
|
||
{"拾", 10},
|
||
{"佰", 100},
|
||
{"千", 1000},
|
||
{"萬", 10000},
|
||
{"億", 100000000},
|
||
{"兆", 1000000000000}
|
||
};
|
||
// 解析中文數字
|
||
public static long ParseChtNum(string chtNumString)
|
||
{
|
||
var isNegative = false;
|
||
if (chtNumString.StartsWith("負"))
|
||
{
|
||
chtNumString = chtNumString.Substring(1);
|
||
isNegative = true;
|
||
}
|
||
long num = 0;
|
||
// 處理千百十範圍的四位數
|
||
Func<string, long> Parse4Digits = (s) =>
|
||
{
|
||
long lastDigit = 0;
|
||
long subNum = 0;
|
||
foreach (var rawChar in s)
|
||
{
|
||
var c = rawChar.ToString().Replace("〇", "零");
|
||
if (ChtNums.Contains(c))
|
||
{
|
||
lastDigit = (long)ChtNums.IndexOf(c);
|
||
}
|
||
else if (ChtUnits.ContainsKey(c))
|
||
{
|
||
if (c == "十" && lastDigit == 0) lastDigit = 1;
|
||
long unit = ChtUnits[c];
|
||
subNum += lastDigit * unit;
|
||
lastDigit = 0;
|
||
}
|
||
else
|
||
{
|
||
throw new ArgumentException($"包含無法解析的中文數字:{c}");
|
||
}
|
||
}
|
||
subNum += lastDigit;
|
||
return subNum;
|
||
};
|
||
// 以兆億萬分割四位值個別解析
|
||
foreach (var splitUnit in "兆億萬".ToArray())
|
||
{
|
||
var pos = chtNumString.IndexOf(splitUnit);
|
||
if (pos == -1) continue;
|
||
var subNumString = chtNumString.Substring(0, pos);
|
||
chtNumString = chtNumString.Substring(pos + 1);
|
||
num += Parse4Digits(subNumString) * ChtUnits[splitUnit.ToString()];
|
||
}
|
||
num += Parse4Digits(chtNumString);
|
||
return isNegative ? -num : num;
|
||
}
|
||
// 轉換為中文數字
|
||
public static string ToChtNum(long n)
|
||
{
|
||
var negtive = n < 0;
|
||
if (negtive) n = -n;
|
||
if (n >= 10000 * ChtUnits["兆"])
|
||
throw new ArgumentException("數字超出可轉換範圍");
|
||
var unitChars = "千佰拾".ToArray();
|
||
// 處理 0000 ~ 9999 範圍數字
|
||
Func<long, string> Conv4Digits = (subNum) =>
|
||
{
|
||
var sb = new StringBuilder();
|
||
foreach (var c in unitChars)
|
||
{
|
||
if (subNum >= ChtUnits[c.ToString()])
|
||
{
|
||
var digit = subNum / ChtUnits[c.ToString()];
|
||
subNum = subNum % ChtUnits[c.ToString()];
|
||
sb.Append($"{ChtNums[(int)digit]}{c}");
|
||
}
|
||
else sb.Append("零");
|
||
}
|
||
sb.Append(ChtNums[(int)subNum]);
|
||
return sb.ToString();
|
||
};
|
||
var numString = new StringBuilder();
|
||
var forceRun = false;
|
||
foreach (var splitUnit in "兆億萬".ToArray())
|
||
{
|
||
var unit = ChtUnits[splitUnit.ToString()];
|
||
if (n < unit)
|
||
{
|
||
if (forceRun) numString.Append("零");
|
||
continue;
|
||
}
|
||
forceRun = true;
|
||
var subNum = n / unit;
|
||
n = n % unit;
|
||
if (subNum > 0)
|
||
numString.Append(Conv4Digits(subNum).TrimEnd('零') + splitUnit);
|
||
else numString.Append("零");
|
||
}
|
||
numString.Append(Conv4Digits(n));
|
||
var t = Regex.Replace(numString.ToString(), "[零]+", "零");
|
||
if (t.Length > 1) t = t.Trim('零');
|
||
t = Regex.Replace(t, "^壹拾", "拾");
|
||
return (negtive ? "負" : string.Empty) + t;
|
||
}
|
||
}
|
||
|
||
|