ASP.NET 生成随机验证码

简介: 我一直觉得用第三方控件生成的验证码太花了,用户体验不好,有的很难看清楚到底是什么,还是那种比较清楚一点的给人的感觉好点。    ///     /// 这个方法用来生成随机验证码    ///     private void ShowCode()    {        Random ran = new Random();        int intRandom = ran.

我一直觉得用第三方控件生成的验证码太花了,用户体验不好,有的很难看清楚到底是什么,还是那种比较清楚一点的给人的感觉好点。
    /// <summary>
    /// 这个方法用来生成随机验证码
    /// </summary>
    private void ShowCode()
    {
        Random ran = new Random();
        int intRandom = ran.Next(10001, 99999);

        //将随机数写入Session
        Session.RemoveAll();
        Session["RandCode"] = intRandom;
        //字体名
        string strFontName = "Arial";
        //字体大小
        int intFontSize = 9;
        //图像宽
        int intWidth = 50;
        //图像长
        int intHeight = 18;
        //背景颜色
        Color bgColor = ColorTranslator.FromHtml("#EFF3FF");
        //前景色
        Color foreColor = ColorTranslator.FromHtml("#00ff00");
        //字体
        Font forFont = new Font(strFontName, intFontSize, FontStyle.Bold);
        //生成图片
        Bitmap newBitmap = new Bitmap(intWidth, intHeight, PixelFormat.Format32bppArgb);
        Graphics g = Graphics.FromImage(newBitmap);
        //定义一个四方形框与字片一样大小
        Rectangle newRect = new Rectangle(0, 0, intWidth, intHeight);
        //背景色
        g.FillRectangle(new SolidBrush(bgColor), newRect);
        //写字
        g.DrawString(intRandom.ToString(), forFont, new SolidBrush(foreColor), 2, 2);
        MemoryStream mStream = new MemoryStream();
        //存入MemoryStream
        newBitmap.Save(mStream, ImageFormat.Gif);
        g.Dispose();
        newBitmap.Dispose();
        //发送
        //Response.ClearContent();
        Response.ContentType = "image/GIF";
        FileStream fis = new FileStream(MapPath("images/") + "yanzheng.gif", FileMode.Create);
        fis.Write(mStream.ToArray(), 0, mStream.ToArray().Length);
        fis.Close();
        this.Image1.ImageUrl = "images/yanzheng.gif";

        //Response.End();
    }

 

在项目里面指定一个文件夹命名为images,这样就OK了。

相关文章
|
开发框架 .NET
asp.net生成验证码并提交验证
asp.net生成验证码并提交验证
162 0
|
JavaScript .NET
ASP.NET ashx实现无刷新页面生成验证码
现在大部分网站登陆时都会要求输入验证码,在网上也看了一些范例,现在总结一下如何实现无刷新页面生成验证码。 效果图:   实现方式: 前台: 1 2 Identifying Code: 3 4 6 8 JS: 1 2...
1081 0