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.Windows.Forms;

namespace 绘制验证码
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string str = null;
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            str = null;
            CreateMap();
        }
        /// <summary>
        /// 绘制验证码图形
        /// </summary>
        void CreateMap()
        {
            //随机产生5个随机数
            Random r = new Random();
            //创建一个位图放在picturebox中
            Bitmap bitmap = new Bitmap(100, 40);
            Graphics g = Graphics.FromImage(bitmap);
            pictureBox1.Image = bitmap;
            pictureBox1.BorderStyle = BorderStyle.FixedSingle;
            string[] fonts = { "微软雅黑", "宋体", "黑体", "隶书", "仿宋" };
            Color[] colors = { Color.Purple, Color.Blue, Color.Black, Color.Red, Color.Green };
            //将随机产生的数字放入bitmap中
            for (int i = 0; i < 5; i++)
            {
                int number = r.Next(0, 10);
                Point point = new Point(i * 20, 0);
                g.DrawString(number.ToString(), new Font(fonts[r.Next(0, 5)], 20, FontStyle.Bold), new SolidBrush(colors[r.Next(0, 5)]), point);
                str += number.ToString();
            }
            //随机绘制直线
            for (int i = 0; i < 40; i++)
            {
                Pen pen = new Pen(new SolidBrush(colors[r.Next(0, 5)]));
                Point p1 = new Point(r.Next(0,bitmap.Width),r.Next(0,bitmap.Height));
                Point p2 = new Point(r.Next(0,bitmap.Width),r.Next(0,bitmap.Height));
                g.DrawLine(pen,p1,p2);
            }
            //随机画像素点
            for (int i = 0; i < 200; i++)
            {
                Point point = new Point(r.Next(0,bitmap.Width),r.Next(0,bitmap.Height));
                bitmap.SetPixel(point.X, point.Y, colors[r.Next(0, 5)]);
            }
        }

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

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == str)
            {
                MessageBox.Show("验证成功!");
            }
            else
            {
                MessageBox.Show("验证码输入有误,请重新输入");
            }
        }
    }
}

实现效果:
验证成功
验证失败

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值