using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace 生成随机验证码
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string path = Application.StartupPath;
string filename = "code.png";
private void button1_Click(object sender, EventArgs e)
{
string data= MakeCode(4);
textBox1.Text= data;
MemoryStream memoryStream= CheckCodeImage(data);
//将图片写入本地 想存就用 不想存就删掉这里
FileStream file = new FileStream(Path.Combine(path,filename), FileMode.OpenOrCreate);
file.Write(memoryStream.GetBuffer(), 0, memoryStream.GetBuffer().Length);
file.Close();//关闭文件
//显示在图片区
Image image = Image.FromStream(memoryStream);
pictureBox1.Image = image;
pictureBox1.Size = new Size(image.Width, image.Height);
}
/// <summary>
/// 生成随机验证码数字+字母
/// </summary>
/// <param name="codelen">验证码长度</param>
/// <returns>返回验证码</returns>
public static string MakeCode(int codelen)
{
if (codelen < 1)
{
return string.Empty;
}
int number;
StringBuilder strCheckCode = new StringBuilder();
Random random = new Random();
for (int index = 0; index < codelen; index++)
{
number = random.Next();
if (number % 2 == 0)
{
strCheckCode.Append((char)('0' + (char)(number % 10)));//生成随机数字
}
else
{
strCheckCode.Append((char)('A' + (char)(number % 26)));//生成随机字母
}
}
return strCheckCode.ToString();
}
public static MemoryStream CheckCodeImage(string CheckCode)
{
if (string.IsNullOrEmpty(CheckCode))
{
return null;
}
Bitmap image = new Bitmap((int)Math.Ceiling((CheckCode.Length * 12.5)), 22);
Graphics graphic = Graphics.FromImage(image);//创建一个验证码图片
try
{
Random random = new Random();
graphic.Clear(Color.White);
int x1 = 0, y1 = 0, x2 = 0, y2 = 0;
for (int index = 0; index < 25; index++)
{
x1 = random.Next(image.Width);
x2 = random.Next(image.Width);
y1 = random.Next(image.Height);
y2 = random.Next(image.Height);
graphic.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));//Font设置字体,字号,字形
//设置图形渐变色的起始颜色与终止颜色,渐变角度
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Red, Color.DarkRed, 1.2f, true);
graphic.DrawString(CheckCode, font, brush, 2, 2);
int X = 0; int Y = 0;
//绘制图片的前景噪点
for (int i = 0; i < 100; i++)
{
X = random.Next(image.Width);
Y = random.Next(image.Height);
image.SetPixel(X, Y, Color.FromArgb(random.Next()));
}
//画图片的边框线
graphic.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
//将图片保存为stream流返回
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms;
}
finally
{
graphic.Dispose();
image.Dispose();
}
}
}
}
04-05