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 验证码
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 点击更换验证码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            GetDraw();
        }
        //记录验证码的值
        string str;
        private void GetDraw()
        {
            str = null;
            //创建随机对象
            Random r = new Random();
            //产生验证码随机数
            for (int i = 0; i < 5; i++)
            {
                int rum = r.Next(0, 10);
                str += rum;
            }
            //绘制图片,将图片放到GDI对象
            Bitmap b = new Bitmap(150, 40);
            创建GDI对象
            Graphics g = Graphics.FromImage(b);

            //产生验证码
            for (int i = 0; i < 5; i++)
            {
                //设置随机验证码的字体
                string[] founts = { "微软雅黑", "宋体", "黑体", "隶属", "仿宋" };
                //设置随机验证码的颜色
                Color[] colors = { Color.Yellow, Color.Red, Color.Black, Color.Green, Color.Black };
                //设置验证码的间距
                Point pic = new Point(i * 30, 0);
                g.DrawString(str[i].ToString(), new Font(founts[r.Next(0, 5)], 15, FontStyle.Bold), new SolidBrush(colors[r.Next(0, 5)]), pic);
            }
            //设置验证码的混淆--线
            for (int i = 0; i < 25; i++)
            {
                Point p1 = new Point(r.Next(0, b.Width), r.Next(0, b.Height));
                Point p2 = new Point(r.Next(0, b.Width), r.Next(0, b.Height));
                g.DrawLine(new Pen(Brushes.Green), p1, p2);
            }
            //设置验证码的混淆--像素点
            for (int i = 0; i < 50; i++)
            {
                Point p = new Point(r.Next(0, b.Width), r.Next(0, b.Height));
                b.SetPixel(p.X, p.Y, Color.Black);
            }
            //将图像对象赋值图片控件
            pictureBox1.Image = b;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            GetDraw();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string text = textBox1.Text.Trim();
            if (text==str)
            {
                MessageBox.Show("登录成功");
                return;
            }
            MessageBox.Show("登录失败");
           
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值