public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
//创建图片对象
Bitmap bmp = new Bitmap(120, 30);
//创建绘制图片的GDI对象
Graphics g = Graphics.FromImage(bmp);
Random r = new Random();
string str = "";
for (int i = 0; i < 5; i++)
{
str += r.Next(0, 10);
}
InstalledFontCollection ff = new InstalledFontCollection();
FontFamily[] family = ff.Families;
for (int i = 0; i < family.Length; i++)
{
comboBox1.Items.Add(family[i]);
}
string[] fonts = { "微软雅黑", "宋体", "楷体", "华文彩云", "黑体" };
Color[] colors = { Color.Yellow, Color.Blue, Color.Black, Color.Green, Color.Red };
//通过一个循环 像图片中画入文本
for (int i = 0; i < 5; i++)
{
Point p = new Point(i * 20, 0);
g.DrawString(str[i].ToString(), new Font(family[r.Next(0,family.Length)], 15), new SolidBrush(colors[r.Next(0,5)]), p);
}
//给图片中画一些直线
for (int i = 0; i < 15; i++)
{
Point p1 = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Height));
Point p2 = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Height));
g.DrawLine(new Pen(Color.Black), p1, p2);
}
////给验证码中加入像素颗粒
for (int i = 0; i < 100; i++)
{
Point p1 = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Height));
bmp.SetPixel(p1.X, p1.Y, Color.Blue);
}
// MessageBox.Show(str);
//将图片放到picturebox上
pictureBox1.Image = bmp;
}
}
|