.Net Core 이미지 인증 코드 구현 예시
아 이 디 어 는 간단 합 니 다="랜 덤 수 생 성-"서버 에 저 장 됩 니 다 Session-"랜 덤 코드 에 대응 하 는 그림 을 생 성하 여 전단-"로그 인 할 때 검사 합 니 다(백 엔 드 에서 랜 덤 코드 의 token 암호 화 를 하고 Cooick 에 저장 하여 전단 에서 검사 할 수도 있 습 니 다)
STEP 1:난수 생 성
private static string RndNum(int VcodeNum)
{
//
string Vchar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,p" +
",q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,P,P,Q" +
",R,S,T,U,V,W,X,Y,Z";
string[] VcArray = Vchar.Split(new Char[] { ',' });//
string code = "";//
int temp = -1;// ,
Random rand = new Random();
//
for (int i = 1; i < VcodeNum + 1; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));//
}
int t = rand.Next(61);//
if (temp != -1 && temp == t)
{
return RndNum(VcodeNum);// ,
}
temp = t;//
code += VcArray[t];//
}
return code;
}
두 번 째 단계:인증 코드 그림 생 성
public static MemoryStream Create(out string code, int numbers = 4)
{
code = RndNum(numbers);
//Bitmap img = null;
//Graphics g = null;
MemoryStream ms = null;
Random random = new Random();
//
Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
//
string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", " " };
using (var img = new Bitmap((int)code.Length * 18, 32))
{
using (var g = Graphics.FromImage(img))
{
g.Clear(Color.White);//
//
for (int i = 0; i < 100; i++)
{
int x = random.Next(img.Width);
int y = random.Next(img.Height);
g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
}
// g
for (int i = 0; i < code.Length; i++)
{
int cindex = random.Next(7);//
int findex = random.Next(5);//
Font f = new Font(fonts[findex], 15, FontStyle.Bold);//
Brush b = new SolidBrush(c[cindex]);//
int ii = 4;
if ((i + 1) % 2 == 0)//
{
ii = 2;
}
g.DrawString(code.Substring(i, 1), f, b, 3 + (i * 12), ii);//
}
ms = new MemoryStream();//
img.Save(ms, ImageFormat.Jpeg);// Png
}
}
return ms;
}
세 번 째 단계:컨트롤 러 호출 방법 으로 난수 그림 을 생 성 한 후 난수 저장
HttpContext.Session.SetString("LoginValidateCode", code);
비고:세 션 을 사용 할 때 세 션 서비스 등록 을 해 야 합 니 다.Configure Services 에서 services.AddSession();
Configure 에서 app.UseSession();
마지막 으로 전단 에서 인증 코드 그림 의 바 인 딩 을 진행 합 니 다.
<img style="justify-content:center" id="code" src="/Users/Login/GetVerifyCode" />
이미지 클릭 하여 인증 코드 리 셋
function GetCode() {
$.ajax({
type: "GET",
url: "/Users/Login/GetVerifyCode",
data: {},
dataType: "json",
success: function (data) {
},
complete: function () {
$("#code").attr('src', '/Users/Login/GetVerifyCode')
}
});
}
SkiaSharp이 바 이 두 의 검색 결 과 는 사용 가능 한 코드 를 준 것 이 하나 도 없다.ε=(´ο`*)))그리고 대부분 혼자 내 놓 은 코드 야.선행 코드
public IActionResult Code()
{
#region SK
//List<SKColor> colors = new List<SKColor>();
//var skcolors = new SKColors();
//var type = skcolors.GetType();
//foreach (FieldInfo field in type.GetFields())
//{
// colors.Add( (SKColor)field.GetValue(skcolors));
//}
#endregion
//int maxcolorindex = colors.Count-1;
string text = "1A3V";
var zu = text.ToList();
SKBitmap bmp = new SKBitmap(80, 30);
using (SKCanvas canvas = new SKCanvas(bmp))
{
//
canvas.DrawColor(SKColors.White);
using (SKPaint sKPaint = new SKPaint())
{
sKPaint.TextSize = 16;//
sKPaint.IsAntialias = true;//
sKPaint.Typeface = SKTypeface.FromFamilyName(" ", SKTypefaceStyle.Bold);//
SKRect size = new SKRect();
sKPaint.MeasureText(zu[0].ToString(), ref size);//
float temp = (bmp.Width/4 - size.Size.Width)/2;
float temp1 = bmp.Height - (bmp.Height - size.Size.Height) / 2;
Random random = new Random();
for (int i = 0; i < 4; i++)
{
sKPaint.Color = new SKColor((byte)random.Next(0,255), (byte)random.Next(0, 255), (byte)random.Next(0, 255));
canvas.DrawText(zu[i].ToString(), temp + 20*i, temp1, sKPaint);//
}
//
for (int i = 0; i < 5; i++)
{
sKPaint.Color = new SKColor((byte)random.Next(0, 255), (byte)random.Next(0, 255), (byte)random.Next(0, 255));
canvas.DrawLine(random.Next(0, 40), random.Next(1, 29), random.Next(41, 80), random.Next(1, 29), sKPaint);
}
}
//
using (SKImage img = SKImage.FromBitmap(bmp))
{
using (SKData p = img.Encode())
{
return File(p.ToArray(), "image/Png");
}
}
}
}
여기 서'Net Core 구현 이미지 인증 코드 의 실현 예시'에 관 한 글 은 여기까지 소개 되 었 습 니 다.더 많은 관련 이 있 습 니 다.Net Core 이미지 인증 코드 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 도 많은 응원 부 탁 드 리 겠 습 니 다!출처:https://www.cnblogs.com/net-open/
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
반사를 이용하여 하나의 클래스에서 속성의 대량 할당 조작을 완성하다메서드 1, 객체 등록 정보가 순차적으로 지정되고 객체 멤버가 변경되면 메서드를 수정합니다. 방법2, 반사를 이용하여 대량으로 값을 부여한다. 객체:/// /// 按钮状态 /// public class ButtonS...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.