欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

深入c#绘制验证码的详解

程序员文章站 2023-12-19 17:55:34
1.使用一个picturebox空间,使用一个按钮,以刷新验证码。2.首先定义checkcode()方法,以生成4为英文及数字组成的字符串序列:复制代码 代码如下:priv...
1.使用一个picturebox空间,使用一个按钮,以刷新验证码。
2.首先定义checkcode()方法,以生成4为英文及数字组成的字符串序列:
复制代码 代码如下:

private string checkcode()
        {
            int number;
            char code;
            string checkcode = string.empty;
            random random = new random();
            for (int i = 0; i < 4; i++)
            {
                number=random.next();
                if(number%2==0)
                    code=(char)('0'+(char)(number%10));
                else
                    code=(char)('a'+(char)(number%26));
                checkcode += " " + code.tostring();
            }
            return checkcode;
        }

3.自定义codeimage()方法,将checkcode()方法生成的序列转化为图片并显示:
复制代码 代码如下:

        private void codeimage(string checkcode)
        {
            if (checkcode == null || checkcode.trim() == string.empty)
            {
                return;
            }
            system.drawing.bitmap image=new system.drawing.bitmap((int)math.ceiling((checkcode.length*50.0)),50);
            graphics g=graphics.fromimage(image);
            try
            {
                random random = new random();
                g.clear(color.white);
                for (int i = 0; i < 3; i++)
                {
                    int x1 = random.next(image.width);
                    int x2 = random.next(image.width);
                    int y1 = random.next(image.height);
                    int y2 = random.next(image.height);
                    g.drawline(new pen(color.black), x1, y1, x2, y2);
                }
                font font = new system.drawing.font("arial", 30, (system.drawing.fontstyle.bold));
                g.drawstring(checkcode, font, new solidbrush(color.red), 2, 2);
                for (int i = 0; i < 200; i++)
                {
                    int x = random.next(image.width);
                    int y = random.next(image.height);
                    image.setpixel(x, y, color.fromargb(random.next()));
                }
                g.drawrectangle(new pen(color.silver), 0, 0, image.width - 1, image.height - 1);
                this.picturebox1.width = image.width;
                this.picturebox1.height = image.height;
                this.picturebox1.backgroundimage = image;
            }
            catch
            {

            }
        }

4.
复制代码 代码如下:

        private void form1_load(object sender, eventargs e)
        {
            codeimage(checkcode());
        }
        private void button1_click(object sender, eventargs e)
        {
            codeimage(checkcode());
        }

上一篇:

下一篇: