• 动态生成验证码


    服务器代码:
    public void ProcessRequest(HttpContext context)
    {
    //context.Response.ContentType = "text/plain";
    //context.Response.Write("Hello World");
    Random rdn = new Random();
    CreateValidateGraphic(rdn.Next(1000, 10000).ToString(), context);
    }
    /// <summary>
    /// 创建验证码的图片
    /// </summary>
    public void CreateValidateGraphic(string validateCode, HttpContext context)
    {
    Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length*12.0),22);
    Graphics g = Graphics.FromImage(image);
    try
    {
    //生成随机生成器
    Random random = new Random();
    //清空图片背景色
    g.Clear(Color.White);
    //画图片的干扰线
    for (int i = 0; i < 25; 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.Silver), x1, y1, x2, y2);
    }
    Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
    System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkBlue, 1.2f, true);
    g.DrawString(validateCode, font, brush, 3, 2);
    //画图片的前景干扰点
    for (int i = 0; i < 100; 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);
    //保存图片的数据
    MemoryStream stream = new MemoryStream();
    image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
    //输出图片流
    context.Response.Clear();
    context.Response.ContentType = "image/Jpeg";
    context.Response.BinaryWrite(stream.ToArray());
    }
    finally
    {
    g.Dispose();
    image.Dispose();
    }
    }
    HTML代码:
    <script type="text/javascript">
    window.onload = function () {
    document.getElementById("aLink").onclick = function () {
    //如果看不清,则重新请求一次一般处理程序,获取一张新图片即可
    document.getElementById("img1").src = 'CreateCode.ashx?id='+Math.random();
    return false;
    };
    };
    </script>
    <body>
    <img src="CreateCode.ashx" id="img1" alt="1"/>
    <a href="#" id="aLink">看不清?</a>
    </body>

    ----以上是在asp.net网站中的应用,mvc版参考:http://www.cnblogs.com/shuai7boy/p/6195134.html

  • 相关阅读:
    Xcode4快速Doxygen文档注释 — 简明图文教程(3分钟后爽歪歪)
    ACE小记
    【C++】获得本机所有网卡的IP和MAC地址信息(转)
    一周好文(11)
    cocos2d‘s replaceScene
    iPhone 真机调试安装流程
    金牌银牌铜牌
    整数分割(摘抄)

    马拦过河卒
  • 原文地址:https://www.cnblogs.com/shuai7boy/p/5536855.html
Copyright © 2020-2023  润新知