zoukankan      html  css  js  c++  java
  • 验证图片生成详细简解

       我详细介绍验证图片的生成,显示简单的字符串显示,详细看以下代码:

    public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentType = "image/jpeg";
                //创建位图,并且给指定边框的宽高
               using (Image img=new Bitmap(80,25))
               {

                  //创建画家对象,在img对象画字符串
                   using (Graphics g=Graphics.FromImage(img))
                   { 
                    //设置位图的背景颜色,默认是黑色
                     g.Clear(Color.White);
                    //设置验证码的宽高, img.Width-1, img.Height-1主要是背景颜色覆盖了边框线
                     g.DrawRectangle(Pens.Black, 0, 0, img.Width-1, img.Height-1);
                       //传100个噪点,传画家对象,位图对象
                     DrawPoint(100, g, img);
                   //画4个验证码的字符串
                   string vcode=GetCode(4);//vcode这里可以赋值给Cookie

                 g.DrawString(vcode,
                  new Font("Arial", 14, FontStyle.Strikeout | FontStyle.Strikeout), // FontStyle字体的样式,多个样式,需要|线          

                    Brushes.Black,
                       new RectangleF(r.Next(20), r.Next(7), img.Width, img.Height));
                   img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//保存验证码对象,指定是Jpeg格式

                   }
               }
            }

         //画噪点方法

            void DrawPoint(int point,Graphics g,Image img)
            {
                for (int i = 0; i < point; i++)
                {
                    int x = r.Next(img.Width);
                    int y = r.Next(img.Width);
                    g.DrawLine(Pens.Red,
                        new Point(x, y),
                        new Point(x+2, y+2));

                }
            }

           //随机数
            Random r = new Random();

          //画字符创
            string GetCode(int point)
            {
                string txtStr = "ASF2345WE5R9F3HMBCZ455K";//这里的string字符串将会转成 char数组,阿拉伯数字1和小写字母l最好别写在里面,会搞胡乱。
                char[] charArr = txtStr.ToArray();
                int num = 0;
                string code = "";
                for (int i = 0; i <point; i++)
                {
                    num = r.Next(charArr.Length);
                    code +=charArr[num];
                }
                return code;
            }

  • 相关阅读:
    DP 免费馅饼 HDU1176
    知了课堂 Python Flask零基础 笔记整理
    Splay入门
    字典树
    榨取kkksc03 多维dp
    种族并查集总结
    倍增总结
    求最大公因数(辗转相除法&更相减损术)
    Bzoj 3036: 绿豆蛙的归宿(期望)
    Bzoj 1497: [NOI2006]最大获利(最小割)
  • 原文地址:https://www.cnblogs.com/janekimyan/p/JanekimYan.html
Copyright © 2011-2022 走看看