下面是一些代码片段:
private void btnTest_Click(object sender, System.EventArgs e)
{
if(int.Parse(txtCode.Text)==(int)Session["Code"])
Response.Redirect("AnotherPage.aspx");//用于测试页
lblStatus.Text="sorry Authentication is not match";
BuildRandom();
}
用于生成随机数。
private void BuildRandom()
{
Random random=new Random();
int AuthenticationCode=random.Next(1000,9999);//产生四位随机数
Session["Code"]=AuthenticationCode;//save in server for authenticate
Code.Src="Code.aspx";
}
最后是一个绘图函数:
Response.ContentType="image/gif";
string text=((int)Session["Code"]).ToString();
Bitmap CodePic=new Bitmap(50,30);
Graphics oGraphics=Graphics.FromImage(CodePic);
DrawText(oGraphics,0,0,50,30,text);
Response.ClearContent();
CodePic.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Gif);
oGraphics.Dispose();
CodePic.Dispose();
}
private void DrawText(Graphics oGraphics,int iTop,int iLeft,int iWidth,int iHeight,string sText)
{
SolidBrush oBrushForBack=new SolidBrush(Color.DeepPink);
oGraphics.FillRectangle(oBrushForBack,0,0,iWidth,iHeight);//将位图刷白
FontStyle eFontStyle=FontStyle.Regular;//字体样式
int iFontSize=8;
string sColor="Black";
StringAlignment eAlign=StringAlignment.Near;
StringFormatFlags eFlag=StringFormatFlags.DirectionVertical;
Rectangle oRect=new Rectangle(iTop,iLeft,iWidth,iHeight);
Font oFont=new Font("Arial",iFontSize,eFontStyle);
StringFormat oFormat=new StringFormat();//字符串格式
oFormat.Alignment=eAlign;//设置字符串格式
oFormat.LineAlignment=StringAlignment.Center;//设置字符串格式
SolidBrush oBrush=new SolidBrush(Color.FromName(sColor));
oGraphics.DrawString(sText,oFont,oBrush,oRect,oFormat);
oBrush.Dispose();
oBrushForBack.Dispose();
}
很简单。在浏览器里执行后,第一次很慢,但后来载入图片就很快了。
浙公网安备 33010602011771号