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 GDI_验证码
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Random r = new Random();
        private void Form1_Load(object sender, EventArgs e)
        {
            setCode(4);
        }
        string conde;
        private void setCode(int length)
        {
             conde= "";
            for (int i = 0; i < length; i++)
            {
                int sss = r.Next(0, 2);
                if (sss == 0)
                {
                    conde += r.Next(0,10);
                }
                else if (sss == 1)
                {
                    conde +=(char) r.Next(97,123);
                }
            }
            if (string.IsNullOrWhiteSpace(conde))
            {
                return;
            }
            Bitmap img = new Bitmap(120,50);
            pictureBox1.Image = img;
            Graphics graphics = Graphics.FromImage(img);
            graphics.Clear(Color.White);
            Pen pen1 = new Pen(Color.Black, 1);
            graphics.DrawRectangle(pen1, 0, 0, img.Width - 1, img.Height - 1);
            string[] fonts = { "微软雅黑", "宋体", "黑体", "隶书", "仿宋" };
           Brush brush = new SolidBrush(Color.FromArgb(r.Next(255), r.Next(255), r.Next(255))); // 随机颜色
            Point point = new Point(0,0);
            
            //绘制随机直线
            for (int i = 0; i < 20; i++)
            {
                Pen pen = new Pen(new SolidBrush(Color.FromArgb(r.Next(255), r.Next(255), r.Next(255))));
                Point p1 = new Point(r.Next(0, img.Width), r.Next(0, img.Height));
                Point p2 = new Point(r.Next(0, img.Width), r.Next(0, img.Height));
                graphics.DrawLine(pen, p1, p2);
            }
            // 绘制随机点
            for (int i = 0; i <conde.Length*40; i++)
            {
                graphics.FillEllipse(brush,r.Next(0,Width), r.Next(0, img.Height), 2, 2);
            }
            // 绘制字符串
             graphics.DrawString(conde, new Font(fonts[r.Next(0, 5)], 22, FontStyle.Bold|FontStyle.Italic), brush, point);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Equals(conde))
            {
                MessageBox.Show("输入正确");
                setCode(4);
            }
            else
            {
                MessageBox.Show("输入错误");
            }
        }
        // 点击图片
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            setCode(4);
        }
    }
}

效果图

在这里插入图片描述

发布了117 篇原创文章 · 获赞 111 · 访问量 9652

猜你喜欢

转载自blog.csdn.net/dust__/article/details/103739599
今日推荐