用心做好每一件事情!

ASP.NET 生成随机验证码

我一直觉得用第三方控件生成的验证码太花了,用户体验不好,有的很难看清楚到底是什么,还是那种比较清楚一点的给人的感觉好点。
    /// <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了。

posted @   无 影  阅读(538)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
作者: Allen【QQ:96966 1314】 网名:无影 出处: http://www.cnblogs.com/allen0118/ 声明: 本文版权归作者和博客园共有!转载时必须保留此段声明,且在文章页面明显位置给出原文连接。
点击右上角即可分享
微信分享提示