コード例 #1
0
        private static Bitmap ProcessImage(Bitmap image, byte blueThreshold = 139)
        {
            try
            {
                var imageClone = image.Clone(new Rectangle(0, 0, image.Width, image.Height), image.PixelFormat);

                var info = new CaptchaInfo();
                imageClone = imageClone.AdjustCurves2()
                             .GetCaptchaInfo(ref info);

                imageClone = image.AdjustCurves2()
                             .CleanUnecessaryPixel(info)
                             .BlackenColor()
                             .CleanUnecessaryPixel(info)
                             .Sharpen();


                return(imageClone);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(null);
        }
コード例 #2
0
        private CaptchaInfo EnsureCaptchaInfo()
        {
            var challengeCode = m_factory.ChallengeCodeProvider().ReadChallengeCode(m_context.Request.Params);

            if (challengeCode == null)
            {
                return(CaptchaInfo.Invalid);
            }

            var ci = new CaptchaInfo()
            {
                ChallengeCode = challengeCode,
                TuringNumber  = m_factory.TuringNumberProvider().NextTuringNumber()
            };

            // Map Challenge with TuringNumber
            if (!m_factory.ChallengeCache().Store(new DataKey <Pair <DateTime, string> >(string.Concat(m_path, challengeCode))
            {
                Value = new Pair <DateTime, string>(DateTime.UtcNow, ci.TuringNumber)
            }, m_maxTimeout))
            {
                ci = CaptchaInfo.Invalid;
            }

            return(ci);
        }
コード例 #3
0
ファイル: PaintForm.cs プロジェクト: swansonk/JediAppADay
 private void button1_Click(object sender, EventArgs e)
 {
     paintableControl1.AllowDraw = false;
     Application.DoEvents();
     try
     {
         CaptchaInfo captcha = _controller.GetCaptcha();
         CaptchaForm f       = new CaptchaForm();
         f.CurrentCaptchaInfo = captcha;
         f.ShowDialog();
         string guess = f.CaptchaGuess;
         byte[] bytes;
         using (MemoryStream ms = new MemoryStream())
         {
             paintableControl1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
             bytes = ms.ToArray();
             ms.Close();
         }
         _controller.SaveImage(bytes, captcha.id, guess);
     }
     catch (Exception ex)
     {
         MessageBox.Show("Error: " + ex.Message);
         return;
     }
     MessageBox.Show("Success, this application will now exit");
     _imageStream.Close();
     Application.DoEvents();
     Close();
 }
コード例 #4
0
        public IHttpActionResult Check(string name, [FromBody] CaptchaInfo captchaInfo)
        {
            try
            {
                var code = CookieUtils.GetCookie("SS-" + name);

                if (string.IsNullOrEmpty(code) || CacheUtils.Exists($"SiteServer.API.Controllers.V1.CaptchaController.{code}"))
                {
                    return(BadRequest("验证码已超时,请点击刷新验证码!"));
                }

                CookieUtils.Erase("SS-" + name);
                CacheUtils.InsertMinutes($"SiteServer.API.Controllers.V1.CaptchaController.{code}", true, 10);

                if (!StringUtils.EqualsIgnoreCase(code, captchaInfo.Captcha))
                {
                    return(BadRequest("验证码不正确,请重新输入!"));
                }

                return(Ok(new
                {
                    Value = true
                }));
            }
            catch (Exception ex)
            {
                LogUtils.AddErrorLog(ex);
                return(InternalServerError(ex));
            }
        }
コード例 #5
0
        private CaptchaInfo CreateCaptcha()
        {
            char[] cText = new char[4];
            cText[0] = (char)_random.Next(97, 123);
            cText[1] = (char)_random.Next(97, 123);
            cText[2] = (char)_random.Next(97, 123);
            cText[3] = (char)_random.Next(97, 123);
            string text = new string(cText);
            Image  img  = new Bitmap(50, 30);

            using (Graphics g = Graphics.FromImage(img))
            {
                g.DrawString(text, _font, _brush, 4, 4);
            }
            byte[] imgBytes;
            using (MemoryStream ms = new MemoryStream())
            {
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                imgBytes = ms.ToArray();
            }
            CaptchaInfo ci = new CaptchaInfo();

            ci.image = imgBytes;
            ci.id    = _random.Next(int.MinValue, int.MaxValue);
            //we add the captcha generated to a cache to lookup upon submission
            //will expire in 30 seconds
            _cache.Add(ci.id.ToString(), text, null, Cache.NoAbsoluteExpiration, _timeSpan, CacheItemPriority.Default, null);
            return(ci);
        }
コード例 #6
0
ファイル: VerifyCodes.cs プロジェクト: HiroHsu/TSFENTLIB
        /// <summary>
        /// 显示验证码图片
        /// </summary>
        public void ToImage()
        {
            string codes = Utils.GetRandCode(4);

            this.pg.Session.Add("VerifyCodes", codes);

            CaptchaInfo captcha = CaptchaProvider.GetInstance().GenerateImage(codes, 200, 40, System.Drawing.Color.WhiteSmoke);

            this.pg.Response.Clear();
            this.pg.Response.ContentType = captcha.ContentType;
            captcha.Image.Save(this.pg.Response.OutputStream, captcha.ImageFormat);
        }
コード例 #7
0
        private bool ValidateCaptcha(string answer, string correctAnswer, string initializationVector, string key)
        {
            var commentWebServiceType     = Type.GetType("Telerik.Sitefinity.Services.Comments.CommentWebService, Telerik.Sitefinity");
            var commentWebServiceInstance = Activator.CreateInstance(commentWebServiceType);
            var validateMethodInfo        = commentWebServiceType.GetMethod("Validate", BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(CaptchaInfo) }, null);

            var captchaInfo = new CaptchaInfo()
            {
                Answer = answer, CorrectAnswer = correctAnswer, InitializationVector = initializationVector, Key = key
            };
            var result = validateMethodInfo.Invoke(commentWebServiceInstance, new object[] { captchaInfo }) as bool?;

            return(result.HasValue && result.Value);
        }
コード例 #8
0
        public void CanRoundTripCaptchaInfo()
        {
            DateTime date =
                DateTime.ParseExact(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture),
                                    "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture);

            var info = new CaptchaInfo("My Test");

            info.WarpFactor    = CaptchaImage.FontWarpFactor.High;
            info.DateGenerated = date;

            string encrypted = info.ToEncryptedString();

            Assert.IsTrue(encrypted.IndexOf("My Test") < 0);
            info = CaptchaInfo.FromEncryptedString(encrypted);
            Assert.AreEqual("My Test", info.Text);
            Assert.AreEqual(CaptchaImage.FontWarpFactor.High, info.WarpFactor);
            Assert.AreEqual(date, info.DateGenerated);
        }
コード例 #9
0
ファイル: CaptchaImpl.cs プロジェクト: fabrimaciel/colosoft
        /// <summary>
        /// Gera um novo captcha
        /// </summary>
        /// <param name="randomText">Texto do captcha</param>
        /// <param name="settings">parâmetros para a geração</param>
        /// <returns></returns>
        public CaptchaInfo Generate(string randomText, CaptchaSettings settings)
        {
            _settings = settings;
            CaptchaInfo  result  = new CaptchaInfo();
            CaptchaImage captcha = new CaptchaImage(randomText, _settings.Width, _settings.Height, _settings.Font);

            using (MemoryStream ms = new MemoryStream())
            {
                captcha.Image.Save(ms, ImageFormat.Jpeg);
                result.Image = ms.ToArray();
                result.Uid   = Guid.NewGuid();
                _pendingCaptcha.Add(result.Uid, new CaptchaStore()
                {
                    Text            = randomText,
                    IsCaseSensitive = _settings.IsCaseSensitive
                });
            }
            return(result);
        }
コード例 #10
0
ファイル: CaptchaController.cs プロジェクト: Harver/cms-1
        public IHttpActionResult Check(string name, [FromBody] CaptchaInfo captchaInfo)
        {
            try
            {
                var code    = CookieUtils.GetCookie("SS-" + name);
                var isValid = StringUtils.EqualsIgnoreCase(code, captchaInfo.Captcha);

                if (!isValid)
                {
                    return(BadRequest("验证码不正确"));
                }

                return(Ok(new OResponse(true)));
            }
            catch (Exception ex)
            {
                LogUtils.AddErrorLog(ex);
                return(InternalServerError(ex));
            }
        }
コード例 #11
0
        private bool ValidateCaptcha(string answer, string correctAnswer, string initializationVector, string key)
        {
            var commentWebServiceType     = Type.GetType("Telerik.Sitefinity.Services.Comments.CommentWebService, Telerik.Sitefinity");
            var commentWebServiceInstance = Activator.CreateInstance(commentWebServiceType);
            var validateMethodInfo        = commentWebServiceType.GetMethod("Validate", BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(CaptchaInfo) }, null);

            var captchaInfo = new CaptchaInfo()
            {
                Answer = answer, CorrectAnswer = correctAnswer, InitializationVector = initializationVector, Key = key
            };
            bool?result;

            // Workaround culture issues in the Captcha validation. Remove this region for Sitefinity 9.0.
            using (new CultureRegion(System.Globalization.CultureInfo.InvariantCulture))
            {
                result = validateMethodInfo.Invoke(commentWebServiceInstance, new object[] { captchaInfo }) as bool?;
            }

            return(result.HasValue && result.Value);
        }
コード例 #12
0
ファイル: OCR.cs プロジェクト: ostrac85/webScraping
        private static System.Drawing.Bitmap ProcessImage(System.Drawing.Bitmap image)
        {
            System.Drawing.Bitmap bitmap = null;
            try
            {
                bitmap = image.Clone(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), image.PixelFormat);
                CaptchaInfo captchaInfo = new CaptchaInfo();
                bitmap = bitmap.AdjustCurves(127).RemoveNoise(new string[]
                {
                    "ff000000"
                }).GetCaptchaInfo(ref captchaInfo);
                System.Drawing.Color c = System.Drawing.ColorTranslator.FromHtml("#" + captchaInfo.CaptchaColor);
                float num       = c.BrightnessLevel();
                byte  threshold = (byte)(80f * num + 50f);
                if (c.B >= 250 && c.R == 0 && c.G == 0)
                {
                    threshold = 144;
                }
                else if (c.B >= 250 && (c.R == 0 || c.G == 0))
                {
                    threshold = 135;
                }
                else if (c.R == 255 && c.G == 255)
                {
                    threshold = 142;
                }
                bitmap = image.AdjustCurves(threshold)
                         .RemoveNoise(new string[] { "ff000000" })
                         .CleanUnecessaryPixel(captchaInfo).GetLongColoredText();

                //bitmap.Save("Test.jpg");
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            }
            return(bitmap);
        }
コード例 #13
0
ファイル: CaptchaController.cs プロジェクト: zhouwybetter/cms
        public IHttpActionResult Check(string name, [FromBody] CaptchaInfo captchaInfo)
        {
            try
            {
                var code = CookieUtils.GetCookie("SS-" + name);
                if (string.IsNullOrEmpty(code))
                {
                    return BadRequest("验证码已超时,请点击刷新验证码图片!");
                }

                if (!StringUtils.EqualsIgnoreCase(code, captchaInfo.Captcha))
                {
                    return BadRequest("验证码不正确,请重新输入!");
                }

                return Ok(new OResponse(true));
            }
            catch (Exception ex)
            {
                LogUtils.AddErrorLog(ex);
                return InternalServerError(ex);
            }
        }
コード例 #14
0
ファイル: CaptchaHandler.cs プロジェクト: kouweizhong/relib
        private CaptchaInfo EnsureCaptchaInfo()
        {
            const string Key = "C";
            var          ci  = m_context.Items[Key] as CaptchaInfo;

            if (ci != null)
            {
                return(ci);
            }

            var challengeCode = m_factory.ChallengeCodeProvider().ReadChallengeCode(m_context.Request.Params);

            if (challengeCode != null)
            {
                ci = new CaptchaInfo();
                ci.ChallengeCode = challengeCode;
                ci.VaryByCustom  = m_factory.VaryByCustomProvider().NextVaryByCustomString();
                ci.TuringNumber  = EnsureTuringNumber(ci.VaryByCustom);

                // Map Challenge with TuringNumber
                if (!m_factory.ChallengeCache().Store(new DataKey <Pair <DateTime, string> >(string.Concat(m_path, challengeCode))
                {
                    Value = new Pair <DateTime, string>(DateTime.UtcNow, ci.TuringNumber)
                }, m_maxTimeout))
                {
                    ci = CaptchaInfo.Invalid;
                }
            }
            else
            {
                ci = CaptchaInfo.Invalid;
            }

            m_context.Items.Add(Key, ci);
            m_factory.InstrumentationProvider().FireIssued(ci.Valid);
            return(ci);
        }
コード例 #15
0
        private async Task GetCode(HttpContext context)
        {
            Random rd = new Random();

            _PositionX = rd.Next(_MinRangeX, _MaxRangeX);
            _PositionY = rd.Next(_MinRangeY, _MaxRangeY);
            context.Session.SetInt32("code", _PositionX);
            context.Session.SetInt32("code_errornum", 0);
            int[]  a     = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };
            int[]  array = a.OrderBy(x => Guid.NewGuid()).ToArray();
            Bitmap bmp;
            var    capchaPic = Path.Combine(path, (new Random()).Next(0, _ImgNum - 1) + ".jpg");
            var    filename  = Path.Combine(environment.ContentRootPath, capchaPic);

            if (!File.Exists(filename))
            {
                var embeddedFileProvider = new Microsoft.Extensions.FileProviders.EmbeddedFileProvider(this.GetType().Assembly, this.GetType().Assembly.GetName().Name);
                var allResources         = embeddedFileProvider.GetDirectoryContents(string.Empty);
                var embedFile            = embeddedFileProvider.GetFileInfo(capchaPic.Replace(Path.DirectorySeparatorChar, '.'));
                if (!embedFile.Exists)
                {
                    throw new ArgumentNullException("can not found captcha picture");
                }
                bmp = new Bitmap(embedFile.CreateReadStream());
            }
            else
            {
                bmp = new Bitmap(filename);
            }
            string ls_small     = "data:image/jpg;base64," + ImgToBase64String(cutImage(bmp, _shearSize, _shearSize, _PositionX, _PositionY));
            Bitmap lb_normal    = GetNewBitMap(bmp, _shearSize, _shearSize, _PositionX, _PositionY);
            string ls_confusion = "data:image/jpg;base64," + ImgToBase64String(ConfusionImage(array, lb_normal));
            var    captchaInfo  = new CaptchaInfo
            {
                Errcode = 0,
                Y       = _PositionY,
                Array   = string.Join(",", array),
                ImgX    = _ImgWidth,
                ImgY    = _ImgHeight,
                Small   = ls_small,
                Normal  = ls_confusion
            };

            /* errcode: 状态值 成功为0
             * y:裁剪图片y轴位置
             * small:小图字符串
             * normal:剪切小图后的原图并按无序数组重新排列后的图
             * array:无序数组
             * imgx:原图宽
             * imgy:原图高
             */

            var viewResult = viewEngine.GetView("~/", "~/Views/Shared/SlideCaptcha.cshtml", true);

            if (viewResult.Success)
            {
                //创建临时的StringWriter实例,用来配置到视图上下文中
                using (var output = new StringWriter())
                {
                    //视图上下文对于视图渲染来说很重要,视图中的前后台交互都需要它
                    var viewContext = new ViewContext()
                    {
                        HttpContext = context,
                        Writer      = output,
                        RouteData   = new Microsoft.AspNetCore.Routing.RouteData()
                        {
                        },
                        ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
                        {
                            Model = captchaInfo
                        },
                        TempData         = new TempDataDictionary(context, tempDataProvider), //ViewData
                        View             = viewResult.View,
                        FormContext      = new FormContext(),
                        ActionDescriptor = new Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor()
                    };
                    //渲染
                    await viewResult.View.RenderAsync(viewContext);

                    var html = output.ToString();
                    context.Response.ContentType = "text/html";
                    //输出到响应体
                    await context.Response.WriteAsync(html);
                }
            }
            else
            {
                await context.Response.WriteAsync(jsonHelper.Serialize(captchaInfo).ToString());
            }
        }
コード例 #16
0
ファイル: CaptchaHelper.cs プロジェクト: TravelerJ/myProject
        /// <summary>
        /// 生成二维码图片
        /// </summary>
        /// <param name="captchaCount"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        public async Task <CaptchaInfo> CreateCaptcha(int captchaCount, int width, int height)
        {
            var model = new CaptchaInfo
            {
                ContentType = ContentType
            };
            var chars  = new char[captchaCount];
            var len    = _characters.Count;
            var random = new Random();

            //随机生成验证码
            for (var i = 0; i < chars.Length; i++)
            {
                var val = random.Next(len);
                chars[i] = _characters[val];
            }
            var captcha = string.Join(string.Empty, chars); //取出验证码

            model.Answer = await Des.Encrypt(captcha);      //加密

            //定义字体集合
            var fontNames = new List <string>
            {
                "Helvetica", "Arial", "Lucida Family", "Verdana", "Tahoma", "Trebuchet MS", "Georgia", "Times"
            };

            // Bitmap 类 封装 GDI + 包含图形图像和其属性的像素数据的位图。 一个 Bitmap 是用来处理图像像素数据所定义的对象。
            //Bitmap 类 继承自 抽象基类 Image 类
            using (var bitmap = new Bitmap(width, height))
            {
                //Graphics 类 封装一个 GDI+ 绘图图面。
                using (var graphics = Graphics.FromImage(bitmap))
                {
                    ///填充背景色
                    graphics.Clear(Color.White);
                    Disturb(random, bitmap, graphics, width / 2, height);

                    //添加灰色边框
                    var pen = new Pen(Color.Silver);
                    graphics.DrawRectangle(pen, 0, 0, width, height);

                    var x = 1;
                    var y = 5;
                    //定义一个矩形
                    var rectanngle = new Rectangle(0, 0, bitmap.Width, bitmap.Height);

                    //随机颜色
                    //var color = Color.FromArgb(random.Next(110, 122), random.Next(110, 122), random.Next(110, 122));

                    foreach (var i in chars)
                    {
                        //随机选择字符 字体 大小
                        var fontName = fontNames[random.Next(0, fontNames.Count - 1)];
                        var font     = new Font(fontName, random.Next(15, 20), FontStyle.Bold | FontStyle.Italic);

                        ///渐变字符颜色
                        using (var brush = new LinearGradientBrush(rectanngle, Color.Blue, Color.DarkRed, 1.2f, true))
                        {
                            brush.SetSigmaBellShape(0.5f);
                            graphics.DrawString(i.ToString(), font, brush, x + random.Next(-2, 2), y + random.Next(-5, 5));
                            x = x + width / captchaCount;
                        }
                    }
                    using (var ms = new MemoryStream())
                    {
                        bitmap.Save(ms, ImageFormat.Jpeg);
                        model.Image = ms.ToArray();
                        return(model);
                    }
                }
            }
        }
コード例 #17
0
 /// <summary>
 /// Validates the post request.
 /// </summary>
 /// <param name="threadType">Type of the thread.</param>
 /// <param name="captchaInfo">The captcha information.</param>
 /// <param name="skipCaptia">if set to <c>true</c> [skip captia].</param>
 public static void ValidatePostRequest(string threadType, CaptchaInfo captchaInfo, bool skipCaptia)
 {
     CommentsWebServiceReflector.ValidatePostRequestReflect(threadType, captchaInfo, skipCaptia);
 }
コード例 #18
0
        private bool ValidateCaptcha(string answer, string correctAnswer, string initializationVector, string key)
        {
            var commentWebServiceType = Type.GetType("Telerik.Sitefinity.Services.Comments.CommentWebService, Telerik.Sitefinity");
            var commentWebServiceInstance = Activator.CreateInstance(commentWebServiceType);
            var validateMethodInfo = commentWebServiceType.GetMethod("Validate", BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(CaptchaInfo) }, null);

            var captchaInfo = new CaptchaInfo() { Answer = answer, CorrectAnswer = correctAnswer, InitializationVector = initializationVector, Key = key };
            var result = validateMethodInfo.Invoke(commentWebServiceInstance, new object[] { captchaInfo }) as bool?;

            return result.HasValue && result.Value;
        }
コード例 #19
0
        private bool ValidateCaptcha(string answer, string correctAnswer, string initializationVector, string key)
        {
            var commentWebServiceType = Type.GetType("Telerik.Sitefinity.Services.Comments.CommentWebService, Telerik.Sitefinity");
            var commentWebServiceInstance = Activator.CreateInstance(commentWebServiceType);
            var validateMethodInfo = commentWebServiceType.GetMethod("Validate", BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(CaptchaInfo) }, null);

            var captchaInfo = new CaptchaInfo() { Answer = answer, CorrectAnswer = correctAnswer, InitializationVector = initializationVector, Key = key };
            bool? result;
            // Workaround culture issues in the Captcha validation. Remove this region for Sitefinity 9.0.
            using (new CultureRegion(System.Globalization.CultureInfo.InvariantCulture))
            {
                result = validateMethodInfo.Invoke(commentWebServiceInstance, new object[] { captchaInfo }) as bool?;
            }

            return result.HasValue && result.Value;
        }