I am using the project of asp.net core3.1 now. I downloaded Bitmap using command.
public class VierificationCodeServices
{
private 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;
}
I'm done with random numbers, how do I insert that background image and font style into it?
CodePudding user response:
You can use this ready-made code:
controller:
[Route("get_captcha")]
[HttpGet]
public Object VerifyCode()
{
string code = "";
Bitmap bitmap = Captcha.CreateCaptcha(out code);
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, ImageFormat.Gif);
return File(stream.ToArray(), "image/gif");
}
Generate verification code and add background style:
public class Captcha
{
public static Bitmap CreateCaptcha(out string code)
{
//Create a Bitmap object and draw
Bitmap bitmap = new Bitmap(200, 60);
Graphics graph = Graphics.FromImage(bitmap);
graph.FillRectangle(new SolidBrush(Color.White), 0, 0, 200, 60);
Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);
Random r = new Random();
string letters = "0123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPPQRSTUVWXYZ";
// string[] VcArray = letters.Split(new Char[] { ',' });
StringBuilder sb = new StringBuilder();
//Add random 4 numbers
for (int x = 0; x < 4; x )
{
string letter = letters.Substring(r.Next(0, letters.Length - 1), 1);
sb.Append(letters);
graph.DrawString(letter, font, new SolidBrush(Color.Black), x * 38, r.Next(0, 15));
}
code = sb.ToString();
//Confuse the background
Pen linePen = new Pen(new SolidBrush(Color.Black), 2);
for (int x = 0; x < 6; x )
graph.DrawLine(linePen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));
return bitmap;
}
}
More usage can read this article:
https://docs.microsoft.com/en-us/dotnet/api/system.drawing.bitmap?view=dotnet-plat-ext-6.0