Files
juipnet/Infrastructure/Hncore.Infrastructure/Common/ValidateCodeHelper.cs
“wanyongkang” ed3b2c653e 接口文件
2024-04-10 13:55:27 +08:00

110 lines
3.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Drawing;
using System.Drawing.Imaging;
namespace Hncore.Infrastructure.Common
{
public class ValidateCodeHelper
{
public static string MakeCode(int length = 4)
{
char[] allCharArray = new char[] { '2', '3', '4', '5', '6', '7', '8', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'W', 'X', 'Y', 'Z' };
string randomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < length; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(allCharArray.Length);
if (temp == t)
{
return MakeCode(length);
}
temp = t;
randomCode += allCharArray[t];
}
return randomCode;
}
public static string MakeNumCode(int length = 4)
{
char[] allCharArray = new char[] { '1','2', '3', '4', '5', '6', '7', '8','9'};
string randomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < length; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(allCharArray.Length);
if (temp == t)
{
return MakeNumCode(length);
}
temp = t;
randomCode += allCharArray[t];
}
return randomCode;
}
public static string MakeCharCode(int length = 4)
{
char[] allCharArray = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'W', 'X', 'Y', 'Z' };
string randomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < length; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(allCharArray.Length);
if (temp == t)
{
return MakeCharCode(length);
}
temp = t;
randomCode += allCharArray[t];
}
return randomCode;
}
public static byte[] GenerateCodeImg(string code)
{
int Gheight = (int)(code.Length * 15) + 10;
//gheight为图片宽度,根据字符长度自动更改图片宽度
using (var img = new Bitmap(Gheight, 22))
{
using (var g = Graphics.FromImage(img))
{
SolidBrush whiteBrush = new SolidBrush(Color.White);
g.FillRectangle(whiteBrush, 0, 0, Gheight, 22);
int i = 0;
foreach (char ch in code.ToCharArray())
{
g.DrawString(ch.ToString(),
new Font("Arial", 13, FontStyle.Italic),
new SolidBrush(Color.FromArgb(0, 0, 0)),
i * 15,
0);
i++;
}
//在矩形内绘制字串字串字体画笔颜色左上x.左上y
System.IO.MemoryStream ms = new System.IO.MemoryStream();
img.Save(ms, ImageFormat.Jpeg);
return ms.ToArray();
}
}
}
}
}