Exemplo n.º 1
0
        public VCodeImgModel Create(string code, int width, int height, ISimCaptchaOptions options)
        {
            VCodeImgModel rtnResult = new VCodeImgModel {
                VCodePos = new List <PointPosModel>()
            };

            // TODO: 变化点: 答案: 4个字
            int rightCodeLength = options.CodeLength;

            Bitmap       Img = null;
            Graphics     g   = null;
            MemoryStream ms  = null;

            Color[] color_Array = { Color.Black, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };

            if (options.Colors != null && options.Colors.Any())
            {
                List <Color> clrLst = new List <Color>();
                foreach (var c in options.Colors)
                {
                    if (c.StartsWith("#"))
                    {
                        try
                        {
                            clrLst.Add(Color.FromArgb(Convert.ToInt32($"FF{ c[1..]}", 16)));
Exemplo n.º 2
0
        private VCodeImgModel CreateVCodeImg()
        {
            VCodeImgModel rtnResult = new VCodeImgModel {
                VCodePos = new List <PointPosModel>()
            };
            string code = RandomCode.Create(this._options);

            rtnResult = VCodeImage.Create(code, 200, 200, this._options);

            return(rtnResult);
        }
Exemplo n.º 3
0
        /// <summary>
        /// 响应验证码,用户会话唯一标识
        /// </summary>
        /// <returns></returns>
        public Task <VCodeResponseModel> VCode()
        {
            VCodeResponseModel rtnResult = new VCodeResponseModel();

            try
            {
                VCodeImgModel model  = CreateVCodeImg();
                string        userId = Guid.NewGuid().ToString();
                rtnResult.code    = 0;
                rtnResult.message = "获取验证码成功";
                rtnResult.data    = new VCodeResponseModel.DataModel
                {
                    userId   = userId,
                    vCodeImg = model.ImgBase64,
                    vCodeTip = model.VCodeTip,
                    words    = model.Words
                };
                // 生成 vCodeKey: 转为json字符串 -> AES加密
                string vCodekeyJsonStr = JsonHelper.Serialize(new VCodeKeyModel
                {
                    ErrorNum = 0,
                    TS       = DateTimeHelper.NowTimeStamp13(),
                    VCodePos = model.VCodePos
                });
                string vCodeKey = _encryptHelper.Encrypt(vCodekeyJsonStr, _options.EncryptKey);
                // 答案 保存到 此次用户会话对应的 Cache 中
                _cacheHelper.Insert <string>(CachePrefixVCodeKey + userId, vCodeKey);
            }
            catch (Exception ex)
            {
                rtnResult.code    = -1;
                rtnResult.message = "获取验证码失败";

                _logHelper?.Write(ex.ToString());
            }

            // TODO: 在.net framework 4.0下未测试
            // Task 参考: https://www.cnblogs.com/yaopengfei/p/8183530.html
#if NETFULL40
            return(Task.Factory.StartNew(() => { return rtnResult; }));
#else
            return(Task.FromResult(rtnResult));
#endif
        }
Exemplo n.º 4
0
        public VCodeImgModel Create(string code, int width, int height)
        {
            VCodeImgModel rtnResult = new VCodeImgModel {
                VCodePos = new List <PointPosModel>()
            };

            // TODO: 变化点: 答案: 4个字
            int rightCodeLength = 4;

            Bitmap       Img    = null;
            Graphics     g      = null;
            MemoryStream ms     = null;
            Random       random = new Random();

            Color[]  color_Array = { Color.Black, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
            string[] fonts       = { "lnk Free", "Segoe Print", "Comic Sans MS", "MV Boli", "华文行楷" };
            // TODO: 可能有错, 在windows, linux下 分割符不同
            string _base = Path.Combine(Environment.CurrentDirectory, "SimCaptcha", "bgImages");
            //string _base = Environment.CurrentDirectory + "\\SimCaptcha\\bgImages\\";

            var _file_List = System.IO.Directory.GetFiles(_base);
            int imageCount = _file_List.Length;

            if (imageCount == 0)
            {
                throw new Exception("image not Null");
            }

            int    imageRandom        = random.Next(1, (imageCount + 1));
            string _random_file_image = _file_List[imageRandom - 1];
            var    imageStream        = Image.FromFile(_random_file_image);

            Img = new Bitmap(imageStream, width, height);
            imageStream.Dispose();
            g = Graphics.FromImage(Img);
            Color[]       penColor    = { Color.LightGray, Color.Green, Color.Blue };
            int           code_length = code.Length;
            List <string> words       = new List <string>();

            for (int i = 0; i < code_length; i++)
            {
                int   cindex = random.Next(color_Array.Length);
                int   findex = random.Next(fonts.Length);
                Font  f      = new Font(fonts[findex], 15, FontStyle.Bold);
                Brush b      = new SolidBrush(color_Array[cindex]);
                int   _y     = random.Next(height);
                if (_y > (height - 30))
                {
                    _y = _y - 60;
                }

                int _x = width / (i + 1);
                if ((width - _x) < 50)
                {
                    _x = width - 60;
                }
                string word = code.Substring(i, 1);
                if (rtnResult.VCodePos.Count < rightCodeLength)
                {
                    (int, int)percentPos = ToPercentPos((width, height), (_x, _y));
                    // 添加正确答案 位置数据
                    rtnResult.VCodePos.Add(new PointPosModel()
                    {
                        X = percentPos.Item1,
                        Y = percentPos.Item2,
                    });
                    words.Add(word);
                }
                g.DrawString(word, f, b, _x, _y);
            }
            rtnResult.Words    = words;
            rtnResult.VCodeTip = "请依次点击: " + string.Join(",", words);

            ms = new MemoryStream();
            Img.Save(ms, ImageFormat.Jpeg);
            g.Dispose();
            Img.Dispose();
            ms.Dispose();
            rtnResult.ImgBase64 = "data:image/jpg;base64," + Convert.ToBase64String(ms.GetBuffer());

            return(rtnResult);
        }
Exemplo n.º 5
0
        public VCodeImgModel Create(string code, int width, int height)
        {
            VCodeImgModel rtnResult = new VCodeImgModel {
                VCodePos = new List <PointPosModel>()
            };

            // TODO: 变化点: 答案: 4个字
            int rightCodeLength = 4;

            Bitmap       bitmap = null;
            Graphics     g      = null;
            MemoryStream ms     = null;
            Random       random = new Random();

            Color[] colorArray = { Color.Black, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };

            string bgImagesDir = Path.Combine(Environment.CurrentDirectory, "SimCaptcha", "bgImages");

            string[] bgImagesFiles = System.IO.Directory.GetFiles(bgImagesDir);

            if (bgImagesFiles == null || bgImagesFiles.Length == 0)
            {
                Console.WriteLine("SimCaptcha/bgImages 需放置背景图片");
                throw new Exception("SimCaptcha/bgImages 需放置背景图片");
            }

            // 字体来自:https://www.zcool.com.cn/special/zcoolfonts/
            string fontsDir = Path.Combine(Environment.CurrentDirectory, "SimCaptcha", "fonts");

            string[] fontFiles = new DirectoryInfo(fontsDir)?.GetFiles()
                                 ?.Where(m => m.Extension.ToLower() == ".ttf")
                                 ?.Select(m => m.FullName).ToArray();
            if (fontFiles == null || fontFiles.Length == 0)
            {
                Console.WriteLine("SimCaptcha/fonts 需放置字体文件 .ttf");
                throw new Exception("SimCaptcha/fonts 需放置字体文件 .ttf");
            }


            int    imgIndex      = random.Next(bgImagesFiles.Length);
            string randomImgFile = bgImagesFiles[imgIndex];
            var    imageStream   = Image.FromFile(randomImgFile);

            bitmap = new Bitmap(imageStream, width, height);
            imageStream.Dispose();
            g = Graphics.FromImage(bitmap);
            Color[]       penColor    = { Color.LightGray, Color.Green, Color.Blue };
            int           code_length = code.Length;
            List <string> words       = new List <string>();

            for (int i = 0; i < code_length; i++)
            {
                int   colorIndex = random.Next(colorArray.Length);
                int   fontIndex  = random.Next(fontFiles.Length);
                Font  f          = LoadFont(fontFiles[fontIndex], 15, FontStyle.Bold);
                Brush b          = new SolidBrush(colorArray[colorIndex]);
                int   _y         = random.Next(height);
                if (_y > (height - 30))
                {
                    _y = _y - 60;
                }

                int _x = width / (i + 1);
                if ((width - _x) < 50)
                {
                    _x = width - 60;
                }
                string word = code.Substring(i, 1);
                if (rtnResult.VCodePos.Count < rightCodeLength)
                {
                    (int, int)percentPos = ToPercentPos((width, height), (_x, _y));
                    // 添加正确答案 位置数据
                    rtnResult.VCodePos.Add(new PointPosModel()
                    {
                        X = percentPos.Item1,
                        Y = percentPos.Item2,
                    });
                    words.Add(word);
                }
                g.DrawString(word, f, b, _x, _y);
            }
            rtnResult.Words    = words;
            rtnResult.VCodeTip = "请依次点击: " + string.Join(",", words);

            ms = new MemoryStream();
            bitmap.Save(ms, ImageFormat.Jpeg);
            g.Dispose();
            bitmap.Dispose();
            ms.Dispose();
            rtnResult.ImgBase64 = "data:image/jpg;base64," + Convert.ToBase64String(ms.GetBuffer());

            return(rtnResult);
        }