日期:2014-05-20  浏览次数:21042 次

如何制作验证码?
就是那种字母数字印在图片上的那种?

------解决方案--------------------
private string GetCode(int num) 

string[] source ={ "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", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}; 
string code = ""; 
Random rd = new Random(); 
for (int i = 0; i < num; i++) 

code += source[rd.Next(0, source.Length)]; 

return code; 

private MemoryStream GetVImageStream() 

MemoryStream ImageMemoryStream = new MemoryStream(); 
string VCodeString = GetCode(4); 
Session["HCValidateCode"] = VCodeString; 
Font VCodeFont = new Font("Arial", 14, FontStyle.Bold); 
SolidBrush VCodeBrush = new SolidBrush(Color.SandyBrown); 
Pen LinePen = new Pen(Color.Ivory, 1); 
Bitmap Tmap = new Bitmap(VCodeString.Length * 19, 24); 
Graphics TGrphics; 
TGrphics = Graphics.FromImage(Tmap); 
TGrphics.Clear(BackGroundColor(0, 255)); 
//产生干扰线 
for (int i = 1; i <= 6; i++) 

int TmpPosition = i * 4; 
Color LineColor = BackGroundColor(0, 255); 
LinePen.Color = LineColor; 
TGrphics.DrawLine(LinePen, 0, TmpPosition, VCodeString.Length * 19, 0); 
LineColor = BackGroundColor(0, 255); 
LinePen.Color = LineColor; 
TGrphics.DrawLine(LinePen, 0, 24, VCodeString.Length * 19, TmpPosition); 

//产生干扰线 
TGrphics.DrawString(VCodeString, VCodeFont, VCodeBrush, VCodeString.Length, 1); 
Tmap.Save(ImageMemoryStream, System.Drawing.Imaging.ImageFormat.Png); 
Tmap.Dispose(); 
TGrphics.Dispose(); 
return ImageMemoryStream; 


#region 随机返回背景色 
/// <summary> 
/// 随机返回颜色 
/// </summary> 
/// <param name="BeginRandomNumber">指定颜色开始的最小值 </param> 
/// <param name="RandomNumber">指定颜色值波动的范围 </param> 
/// <returns>随机的Color </returns> 
private Color BackGroundColor( int BeginRandomNumber , int RandomNumber ) 

int ColorR = 0 ; 
int ColorG = 0 ; 
int ColorB = 0 ; 
Random TRandom = new Random() ; 
ColorR = BeginRandomNumber + TRandom.Next( RandomNumber ) ; 
ColorG = BeginRandomNumber + TRandom.Next( RandomNumber ) ; 
ColorB = BeginRandomNumber + TRandom.Next( RandomNumber ) ; 
Color ColorBG = Color.FromArgb( ColorR , ColorG , ColorB ) ; 
return ColorBG ; 

#endregion 


Response.ClearContent();