.NET封装类库 生成验证码【适用于MVC/ASP.NET/控制台项目】

     private  const string StrWord = "123456789QWERTYUIOPASDFGHJKLZXCVBNM";
        # region  MVC写法
        //public IActionResult GetValidateImg()
        //{
        //    Random RandomSeed = new Random();
        //    string strWord = "123456789QWERTYUIOPASDFGHJKLZXCVBNM";
        //    string numStr = null;
        //    for (int i = 0; i < 5; i++)
        //    {
        //        numStr += strWord[RandomSeed.Next(0, strWord.Length)];
        //    }
        //    HttpContext.Session.SetString("vcode", numStr.ToLower().ToString());
        //    int iwidth = numStr.Length * 13;
        //    Bitmap image = new Bitmap(iwidth, 22);
        //    Graphics g = Graphics.FromImage(image);
        //    g.Clear(Color.White);
        //    Color[] colors = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan };
        //    string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
        //    Random rand = new Random();
        //    for (int i = 0; i < 50; i++)
        //    {
        //        int x = rand.Next(image.Width);
        //        int y = rand.Next(image.Height);
        //        g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
        //    }
        //    for (int i = 0; i < numStr.Length; i++)
        //    {
        //        int cIndex = rand.Next(7);
        //        int fIndex = rand.Next(5);
        //        Font f = new System.Drawing.Font(font[fIndex], 10, FontStyle.Bold);
        //        Brush b = new System.Drawing.SolidBrush(colors[cIndex]);
        //        int ii = 4;
        //        if ((i + 1) % 2 == 0)
        //        {
        //            ii = 2;
        //        }
        //        g.DrawString(numStr.Substring(i, 1), f, b, 2 + (i * 12), ii);
        //    }
        //    g.DrawRectangle(new Pen(ColorTranslator.FromHtml("#CCCCCC"), 0), 0, 0, image.Width - 1, image.Height - 1);
        //    System.IO.MemoryStream ms = new System.IO.MemoryStream();//保存到内存当中
        //    try
        //    {
        //        image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);//把图片以jpeg保存到ms流当中
        //        return File(ms.ToArray(), "image/gif");
        //    }
        //    catch (Exception)
        //    {
        //        return null;
        //    }
        //    finally
        //    {
        //        g.Dispose();
        //        image.Dispose();
        //    }
        //}
        //public string GetSession()
        //{
        //    return HttpContext.Session.GetString("vcode");
        //}
        #endregion


        /// <summary>
        /// 传入需要生成的验证码内容,无内容则按照默认规则生成验证码图片
        /// </summary>
        /// <param name="vcode"><验证码内容/param>
        /// <returns>返回验证码图片</returns>
        public static Image GetValidateImg(string vcode="")
        {
            Random random = new Random();
            if (string.IsNullOrWhiteSpace(vcode))
            {
                for (int i = 0; i < 5; i++)
                {
                    vcode += StrWord[random.Next(0, StrWord.Length)];
                }
            }
            int iwidth = vcode.Length * 13;
            Bitmap image = new Bitmap(300, 300);
            Graphics g = Graphics.FromImage(image);
            g.Clear(Color.White);
            Color[] colors = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan };
            string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
            int x = 0, y = 0, cIndex = 0, fIndex = 0;
            for (int i = 0; i < 50; i++)
            {
                x = random.Next(image.Width);
                y = random.Next(image.Height);
                g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
            }
            for (int i = 0; i < vcode.Length; i++)
            {
                cIndex = random.Next(7);
                fIndex = random.Next(5);
                Font f = new System.Drawing.Font(font[fIndex], 10, FontStyle.Bold);
                Brush b = new System.Drawing.SolidBrush(colors[cIndex]);
                int ii = 4;
                if ((i + 1) % 2 == 0)
                {
                    ii = 2;
                }
                g.DrawString(vcode.Substring(i, 1), f, b, 2 + (i * 12), ii);
            }
            g.DrawRectangle(new Pen(ColorTranslator.FromHtml("#CCCCCC"), 0), 0, 0, image.Width - 1, image.Height - 1);
            SaveImage(image,ImgKind.ValidateCode);
            return image;
        }

  /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="image"></param>
        private static void SaveImage(Image image,ImgKind kind)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                try
                {
                    image.Save(stream, ImageFormat.Jpeg);
                    File.WriteAllBytes(Path.Combine(System.Environment.CurrentDirectory,$"{kind.GetRemark()}.Jpeg"), stream.ToArray());
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }


        /// <summary>
        /// 图片种类
        /// </summary>
        private enum ImgKind
        { 
            /// <summary>
            /// 验证码
            /// </summary>
            [Remark("验证码")]
            ValidateCode=1,
            /// <summary>
            /// 二维码
            /// </summary>
            [Remark("二维码")]
            QRCode =2
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BUG呢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值