Create a new page image.aspx and add the namespace:
using System.Drawing.Imaging;
using System.IO;
Then copy the following code in the Page_load event:
//Generate a 4-digit verification code
string tmp = RndNum(4);
HttpCookie a = new HttpCookie("ImageV",tmp);
Response.Cookies.Add(a);
this.ValidateCode(tmp);
Next add two methods to the page:
private void ValidateCode(string VNum)
{
Bitmap Img=null;
Graphics g=null;
MemoryStream ms=null;
int gheight=VNum.Length*12;
Img=new Bitmap(gheight,25);
g=Graphics.FromImage(Img);
//Background color
g.Clear(Color.White);
//Text font
Font f=new Font("Arial Black",10);
//Text color
SolidBrush s=new SolidBrush(Color.Black);
g.DrawString(VNum,f,s,3,3);
ms=new MemoryStream();
Img.Save(ms,ImageFormat.Jpeg);
Response.ClearContent();
Response.ContentType="image/Jpeg";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
Img.Dispose();
Response.End();
}
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,o,p"+
",q,r,s,t,u,v,w,x,y,z";
string[] VcArray=Vchar.Split(new Char [] {','});
string VNum="";
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(35);
if(temp!=-1&&temp==t)
{
return RndNum(VcodeNum);
}
temp=t;
VNum+=VcArray[t];
}
return VNum;
}
If you want to generate a verification code on page a.aspx, add an image control to the page, assuming it is named: ImageButton1, and then write the following code in the page_Load event:
ImageButton1.ImageUrl = "image.aspx";
This way you can generate The verification code is provided. The image.aspx page can be placed anywhere, but please note that the ImageButton1.ImageUrl must be written correctly. The same level can directly write image.aspx, and the upper level can write ../image.aspx. It is very convenient.