C#制作验证码

时间:2023-11-23 16:29:50
 void CodeImage(string code)
{
if (code == null || code.Trim() == string.Empty)
return;
System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling(code.Length * 11.0), );
Graphics g = Graphics.FromImage(image);
try
{
Random rdm = new Random();
g.Clear(Color.White);
//画图片的背景噪音线
for (int i = ; i < ; i++)
{
int x1 = rdm.Next(image.Width);
int x2 = rdm.Next(image.Width);
int y1 = rdm.Next(image.Height);
int y2 = rdm.Next(image.Height);
g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
}
Font font = new System.Drawing.Font("Arial", , FontStyle.Bold);
g.DrawString(code, font, new SolidBrush(Color.Red), , );
//画前景噪音线
for (int i = ; i < ; i++)
{
int x = rdm.Next(image.Width);
int y = rdm.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(rdm.Next()));
}
g.DrawRectangle(new Pen(Color.Silver), , , image.Width - , image.Height - );
pictureBox1.Width = image.Width;
pictureBox1.Height = image.Height;
pictureBox1.Image = image;
}
catch
{ }
}