用C#生成验证码

2009年3月12日星期四

用C#生成验证码

// 构造一个rLength长度的数字串,作为验证码
public static string BuildRndInt(int rLength)
{
System.Random rnd = new Random();
string code = "";
for(int i=0;i9)
num = rnd.Next(10);
code += num+"";
}
return code;
}

//输出一个带有文字内容的图片
// rMarkText 每段文字分行显示
public void BuildTextWatermarkImg(string[] rMarkText,string rAlign,Stream rDstStream)
{
if(rMarkText==null rMarkText.Length<1)return; tmpphoto="new" tmpgr =" Graphics.FromImage(tmpPhoto);" crfont =" null;" crsize =" new" crfont =" new" crsize =" tmpGr.MeasureString(rMarkText[0],crFont);" imgwidth =" (int)crSize.Width+20;" imgheight =" (int)crSize.Height+4;" fontheight =" imgHeight;" arrwidth =" new" i="1;igt;rmarktext.length;i++)" crsize="tmpGr.MeasureString(rMarkText[i],crFont);">imgWidth)imgWidth= (int)(crSize.Width);
arrWidth[i] = crSize.Width;
}
tmpPhoto.Dispose();
tmpGr.Dispose();


Bitmap bmPhoto=new Bitmap(imgWidth,imgHeight, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(72,72);

Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
grPhoto.DrawRectangle(new Pen(Color.White),new Rectangle(0, 0, imgWidth, imgHeight));
grPhoto.Clear(Color.White);
//grPhoto.FillRectangle(new SolidBrush(Color.White),new Rectangle(0, 0, imgWidth, imgHeight));

for(int i=0;i {
StringFormat StrFormat = new StringFormat();
StrFormat.Alignment = StringAlignment.Center;

int ypos;
if(i==0)
ypos = 0;
else
ypos = i*fontHeight+2;

PointF pf = new PointF(0,0);
if(rAlign=="center")
{
pf = new PointF(imgWidth/2,ypos);
}
else if(rAlign=="left")
{
pf = new PointF((arrWidth[i]/2),ypos);
}
else if(rAlign=="right")
{
pf = new PointF( (imgWidth-(arrWidth[i]/2)),ypos);
}
else
{
pf = new PointF(imgWidth/2,ypos);
}
grPhoto.DrawString(rMarkText[i],
crFont,
new SolidBrush(Color.FromArgb(255, 255, 0,0)) ,
pf,
StrFormat);
}

bmPhoto.Save(rDstStream,ImageFormat.Gif);
bmPhoto.Dispose();
grPhoto.Dispose();
}
//输出带有验证码的图片
private void GetCodeImg()
{
string[] code = new string[]{""};
code[0]=CommUtil.BuildRndInt(4);
//这个处理验证码
ImgUtil iu = new ImgUtil();
Response.ContentType = "image/jpeg";
iu.BuildTextWatermarkImg(code,"center",Response.OutputStream);
//Response.Write(code[0]);
Response.End();
}

0 评论:

发表评论