- 验证码源代码实现c#谢谢阿!!
- 谢谢阿!!
- using ;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;
///
/// Summary description for yanzhengma
///
public class Yanzhengma
{
private string GetRandom()
{
int number;
char charCode;
string strCode = string.Empty;
System.Random random = new System.Random();
for (int i = 1; i <= 5; i++)
{
number = random.Next();
if (number % 2 == 0)
{
charCode = (char)('0' + (char)(number % 10));
}
else
{
charCode = (char)('A' + (char)(number % 26));
}
strCode += charCode.ToString();
}
// System.Web.HttpContext.Current.Response.Cookies
HttpContext.Current.Response.Cookies.Add(new HttpCookie("codebycookies", strCode));
return strCode;
}
public void DrawRandom()
{
string strCode = GetRandom();
Bitmap image = new Bitmap(100, 30);
Graphics huatu = Graphics.FromImage(image);
try
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
huatu.Clear(Color.White);
//画图片的背景噪音线
int x1, x2, y1, y2;
for (int i = 0; i < 10; i++)
{
x1 = random.Next(image.Width);
x2 = random.Next(image.Width);
y1 = random.Next(image.Height);
y2 = random.Next(image.Height);
huatu.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font font = new Font("Arial", 20, (FontStyle.Bold | System.Drawing.FontStyle.Italic));
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
huatu.DrawString(strCode, font, brush, 2, 2);
//画图片的前景噪音点
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画图片的边框线
huatu.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width, image.Height);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
}
finally
{
huatu.Dispose();
image.Dispose();
}
}
}