ASP.NET 创建验证码字符及图片

0.

在网页中经常需要输入验证码,那么自己该如何做一个类似效果呢?

1.

代码如下。我使用的是web窗体

        protected void Button1_Click(object sender, EventArgs e) {
            Bitmap b = createImageBy_verifycationText(createVerifycationText(6) , 400 , 100);
            //ASP.NET 中使用 image控件显示 Bitmap 
            //好奇怪,image控件并没有类似background的属性,显示Bitmap还要拐弯抹角
            using (MemoryStream stream = new MemoryStream()) {
                b.Save(stream , ImageFormat.Png);
                String base64 = Convert.ToBase64String(stream.ToArray());
                Image1.ImageUrl = "data:image/png;base64,"+base64;
            }
        }

        //创建验证码字符,Length为字符串长度,一般设置6位
        public static String createVerifycationText(int Length) {
            char[] _verifycation = new char[Length];
            char[] _dictionary = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
                'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
            Random _randon = new Random();
            for (int i = 0; i<Length; i++) {
                _verifycation[i] = _dictionary[_randon.Next(_dictionary.Length-1)];
            }
            return new String(_verifycation);
        }
        //根据验证码字符串 创建 Bitmap
        public static Bitmap createImageBy_verifycationText(String verifycationText , int width , int height) {
            Pen _pen = new Pen(Color.Black);
            Font _font = new Font("Arial" , 30 , FontStyle.Bold);
            Brush _brush = null;
            Bitmap _bitmap = new Bitmap(width , height);
            Graphics _g = Graphics.FromImage(_bitmap);
            SizeF _totalSizeF = _g.MeasureString(verifycationText , _font);
            SizeF _curCharSizeF;
            PointF _startPointF = new PointF((width-_totalSizeF.Width)/2 , (height-_totalSizeF.Height)/2);
            //随机数产生颜色
            Random _random = new Random();
            _g.Clear(Color.Gray);
            for (int i = 0; i < verifycationText.Length; i++) {
                _brush = new LinearGradientBrush(new PointF(0,0) , new PointF(1,1) , Color.FromArgb(_random.Next(255) , _random.Next(255) , _random.Next(255)) , Color.FromArgb(_random.Next(255), _random.Next(255), _random.Next(255)));
                _g.DrawString(verifycationText[i].ToString() , _font , _brush , _startPointF);
                _curCharSizeF = _g.MeasureString(verifycationText[i].ToString() , _font);
                _startPointF.X += _curCharSizeF.Width;
            }
            _g.Dispose();
            return _bitmap;
        }

2.

效果

猜你喜欢

转载自blog.csdn.net/qq_38261174/article/details/86654271