当前位置:首页 > 随机验证图片的产生,asp.net 2.0 c# —在网页的特定或莫个位置显示图片

随机验证图片的产生,asp.net 2.0 c# —在网页的特定或莫个位置显示图片

点击次数:945  更新日期:2010-12-28
\n

1.把下面的代码放到类中
/**//// <summary>
/// 生成随机数
/// </summary>
/// <returns></returns>
private string GenerateCheckCode()
{
#region
int number;
char code;
string checkCode = String.Empty;


\n

System.Random random = new Random();


\n

for (int i = 0; i < 5; i++)
{
number = random.Next();


\n

if (number % 2 == 0)
code = (char)(’0′ + (char)(number % 10));
else
code = (char)(‘A’ + (char)(number % 26));


\n

checkCode += code.ToString();
}


\n

HttpContext.Current.Response.Cookies.Add(new HttpCookie(“CheckCode”, checkCode));


\n

return checkCode;
#endregion
}


\n


/**//// <summary>
/// 生成验证码图片
/// </summary>
public void CreateCheckCodeImage()
{
#region
string checkCode = GenerateCheckCode();
if (checkCode == null || checkCode.Trim() == String.Empty)
return;


\n

System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
Graphics g = Graphics.FromImage(image);


\n

try
{
//生成随机生成器
Random random = new Random();


\n

//清空图片背景色
g.Clear(Color.White);


\n

//画图片的背景噪音线
for (int i = 0; i < 25; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);


\n

g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}


\n

Font font = new System.Drawing.Font(“Arial”, 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, font, brush, 2, 2);


\n

//画图片的前景噪音点
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);


\n

image.SetPixel(x, y, Color.FromArgb(random.Next()));
}


\n

//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width – 1, image.Height – 1);


\n

System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ContentType = “image/Gif”;
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
#endregion
}


\n

2.
如果你要显示图片显示在一张网页上只要新建一张网页CheckImg.aspx调用上面的代码就行了,


\n

3.但是你如果想把这张图片显示在网页的莫个地方就需要修改一下,那么就要新建一张网页用来显示上面的那张网页ImageUrl=”~/CheckImg.aspx”,把下面的代码放到这张新的页面中,那么图片就会在image控件中显示
<asp:Image ID=”Image1″ runat=”server” ImageUrl=”~/CheckImg.aspx” />


\n

来源:CSDN

\n