zoukankan      html  css  js  c++  java
  • 自己动手写验证码

    *******************************************处理程序(CheckCode.ashx)***************************/ public class CheckCode : IHttpHandler,System.Web.SessionState.IRequiresSessionState //注意处理程序应用session需要的System.Web.SessionState.IRequiresSessionState接口 {

    public void ProcessRequest (HttpContext context) {

    context.Response.ContentType = "image/jpeg";

    using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(80, 30)) {

    using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap)) {

    g.DrawString("你好吗",new System.Drawing.Font("宋体",20), System.Drawing.Brushes.Green ,new System.Drawing.PointF(0,0) );

     System.Drawing.Pen pen= (System.Drawing.Pen)System.Drawing.Pens.Red.Clone();

     pen.Width=5;

    g.DrawEllipse(pen,new System.Drawing.Rectangle(10,10,10,10)); bitmap.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);//上面是自己手写的图片

    Random r = new Random();

    int random=r.Next(0,9999);

    string code = random.ToString();

    HttpContext.Current.Session["code"] = code;//数字验证码

    byte[] bytes = new byte[100];

    Random randObj = new Random();

    int code;

    for (int i = 0; i < 4; i++) {

    code = randObj.Next(44, 122); bytes[i] = Convert.ToByte(code);

    }

    System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();

    string validateCode = ascii.GetString(bytes, 0, 4);

    string strcode= validateCode.ToString();//根据ASCII码随机获取的验证码

    g.DrawString(code,new System.Drawing.Font("宋体",20),System.Drawing.Brushes.Green,new System.Drawing.PointF(0,0)); bitmap.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);

    }

    } }

    /*******************************************页面对验证码的应用***************************/

    <form id="form1" runat="server"> <div> <img src="CheckCode.ashx" onclick="this.src='CheckCode.ashx?date='+new Date()" />//点击验证码一次回传给ashx一次,刷新一下验证码(注意参数为时间不会一样的) <br />

    </div>

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="确定" onclick="Button1_Click" />

    </form>

    protected void Button1_Click(object sender, EventArgs e) {

    if (TextBox1.Text == Session["code"].ToString()) { Response.Write("验证通过!"); } else { Response.Write("验证失败!");

    }

    }

  • 相关阅读:
    BZOJ 1562 [NOI2009] 变换序列
    BZOJ 2535:NOI 2010 航空管制
    C++ 莫队算法(转)
    SDOI2013直径(树的直径)
    c++分块算法(暴力数据结构)
    洛谷题解 P2865 【[USACO06NOV]路障Roadblocks】
    c++最短路经典问题
    LOJ#10065. 「一本通 3.1 例 2」北极通讯网络
    最小生成树(kruscal算法)
    飞屋环游记
  • 原文地址:https://www.cnblogs.com/sybboy/p/2863215.html
Copyright © 2011-2022 走看看