天天看點

C# 使用GDI繪制驗證碼

C# 使用GDI繪制驗證碼

源碼如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GDIDrawCaptcha
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            pictureBox1_Click(sender, e);
        }
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            // 建立GDI對象
            Bitmap bmp = new Bitmap(150, 40);
            Graphics g = Graphics.FromImage(bmp);

            Random r = new Random();
            string[] fonts = { "微軟雅黑", "宋體", "黑體", "隸書", "仿宋", "Arial", "新宋體", "隸書" };
            Brush[] brushes = { Brushes.DimGray, Brushes.Blue, Brushes.Black, Brushes.Red, Brushes.Green, Brushes.AliceBlue, Brushes.Gold, Brushes.LightPink };
            // 畫數字
            string str = null;
            for (int i = 0; i < 5; i++)
            {
                int rNumber = r.Next(0, 10);
                str += rNumber;
            }
            for (int i = 0; i < 5; i++)
            {
                Point p = new Point(i * 30, 5);
                g.DrawString(str[i].ToString(), new Font(fonts[r.Next(0, 8)], 20, FontStyle.Bold), new SolidBrush(Color.FromArgb(r.Next(0, 255), r.Next(0, 255), r.Next(0, 255))), p);
            }
            // 劃線
            for (int i = 0; i < 20; 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(brushes[r.Next(0, 8)]), p1, p2);
            }
            // 畫點
            for (int i = 0; i < 500; i++)
            {
                Point p=new Point(r.Next(0,bmp.Width),r.Next(0,bmp.Height));
                bmp.SetPixel(p.X, p.Y, Color.FromArgb(r.Next(0, 255), r.Next(0, 255), r.Next(0, 255)));
            }
            //将圖檔鑲嵌到PictureBox中
            pictureBox1.Image = bmp;
            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
        }
    }
}
           
c#