private async System.Threading.Tasks.Task SetVerificationCode(ValidationData validationData, string picFilePath, string clientKey) { DebugHelper.VerboseMode = true; var api = new ImageToText(NumericOption.NumbersOnly, 0) { ClientKey = clientKey, FilePath = picFilePath }; if (!api.CreateTask()) { DebugHelper.Out("API v2 send failed. " + api.ErrorMessage, DebugHelper.Type.Error); } else if (!api.WaitForResult()) { DebugHelper.Out("Could not solve the captcha.", DebugHelper.Type.Error); } else { var result = api.GetTaskSolution().Text; DebugHelper.Out("Result: " + result, DebugHelper.Type.Success); validationData.TextBox1 = result; } }
public static string EvaluateImage(string urlToProcess) { var client = Clients.NewClient(); EvaluationData imageData = ImageToText.EvaluateImage(client, urlToProcess); return(imageData.TextDetection.Text); }
public async Task TestFullPipeline() { var visionApiKey = System.Environment.GetEnvironmentVariable("VISION_API_KEY"); Assert.IsFalse(string.IsNullOrWhiteSpace(visionApiKey), "Must provide API Key"); var luisApp = System.Environment.GetEnvironmentVariable("LUIS_APP_ID"); Assert.IsFalse(string.IsNullOrWhiteSpace(luisApp), "Must provide app ID"); var luisApiKey = System.Environment.GetEnvironmentVariable("LUIS_API_KEY"); Assert.IsFalse(string.IsNullOrWhiteSpace(luisApiKey), "Must provide API Key"); var mordorImage = "http://i.imgur.com/5ocZvsW.jpg"; var imageToText = new ImageToText(visionApiKey); var result = await imageToText.ProcessImageToTextAsync(await ImageUtilities.SingleChannelAsync(new Uri(mordorImage), ImageUtilities.Channel.Blue)); var lines = ImageToText.ExtractLinesFromResponse(result).ToList(); lines.RemoveAt(lines.Count - 1); // Remove memegenerator.net line. var text = string.Join(" ", lines); var luis = new TextToEntitiesAndIntent(luisApp, luisApiKey); var luisResult = await luis.DetectEntitiesAndIntentFromText(text); Trace.TraceInformation(luisResult.ToString(Newtonsoft.Json.Formatting.Indented)); Assert.IsNotNull(luisResult); }
public string ReadImage(string filepath, string apiKey) { string captchaText = string.Empty; var api = new ImageToText { ClientKey = apiKey, FilePath = filepath }; if (!api.CreateTask()) { Console.WriteLine("API v2 send failed. " + api.ErrorMessage ?? "", DebugHelper.Type.Error); } else if (!api.WaitForResult()) { DebugHelper.Out("Could not solve the captcha.", DebugHelper.Type.Error); } else { captchaText = api.GetTaskSolution(); DebugHelper.Out("Result: " + captchaText, DebugHelper.Type.Success); } return(captchaText); }
private async Task MessageReceivedAsync(SocketMessage message) { if (message.Author.Id == _client.CurrentUser.Id) { return; } // Check if the message is a captcha request if (message.Content.Contains(_CAPTCHA_REQUEST_PATTERN)) { IReadOnlyCollection <Attachment> msgAttachments = message.Attachments; IReadOnlyCollection <SocketUser> msgMentionnedUser = message.MentionedUsers; // ID of the user that needs a captcha bypass ulong userId = msgMentionnedUser.ElementAt(0).Id; string userName = msgMentionnedUser.ElementAt(0).Username; // Sends bypass request to DB wcSendToServer.DownloadString($"http://127.0.0.1/needCaptcha.php?idDiscord={userId}"); Console.WriteLine($"[Captcha] Captcha Request for User {userName} ({userId})"); // Getting captcha image link string imgUrl = msgAttachments.ElementAt(0).Url; // Downloading captcha image using (WebClient client = new WebClient()) { client.DownloadFile(new Uri(imgUrl), System.Environment.CurrentDirectory + $"/toBypass/{userId}.png"); } // Captcha Bypass var api = new ImageToText { ClientKey = _CAPTCHA_API_KEY, FilePath = System.Environment.CurrentDirectory + $"/toBypass/{userId}.png" }; if (!api.CreateTask()) { Console.WriteLine($"[Captcha] API send FAIL -> [{api.ErrorMessage}]"); } else if (!api.WaitForResult()) { Console.WriteLine($"[Captcha] Couldn't solve captcha..."); } else { Console.WriteLine($"[Captcha] Captcha Solved for User {userName} ({userId}) -> [{api.GetTaskSolution().Text}]"); string captcha = api.GetTaskSolution().Text; captcha = captcha.Replace("\"", ""); wcSendToServer.DownloadString($"http://127.0.0.1/insertCaptcha.php?idDiscord={userId}&captcha={captcha}"); await message.Channel.SendMessageAsync("Captcha Result : " + captcha); } } }
// Dispose ImageToText object. private void DestroyImageConverter() { if (AsciiArtist != null) { AsciiArtist.Dispose(); AsciiArtist = null; } }
public void TestExtractLinesFromResponse() { // Copied (and pruned) from Project Oxford OCR example response: https://dev.projectoxford.ai/docs/services/54ef139a49c3f70a50e79b7d/operations/5527970549c3f723cc5363e4 var response = JObject.Parse(ExampleResponse); var expected = new[] { "Set an example.", "you are.", "Spiril Science" }; var lines = ImageToText.ExtractLinesFromResponse(response).ToArray(); CollectionAssert.AreEqual(expected, lines); }
public void TestExtractTextFromResponse() { // Copied (and pruned) from Project Oxford OCR example response: https://dev.projectoxford.ai/docs/services/54ef139a49c3f70a50e79b7d/operations/5527970549c3f723cc5363e4 var response = JObject.Parse(ExampleResponse); var expected = "Set an example. you are. Spiril Science"; var actual = ImageToText.ExtractTextFromResponse(response); Assert.AreEqual(expected, actual); }
private void BuscaCaptchaString() { var text = wb.Document.GetElementById("cipCaptchaImg"); var html = String.Format("{0}{1}{2}", "<table cellpadding=\"0\" cellspacing=\"0\">", text.InnerHtml, "</table>"); var htmlToImageConv = new NReco.ImageGenerator.HtmlToImageConverter(); // htmlToImageConv.Height = 70; htmlToImageConv.Width = 200; var jpegBytes = htmlToImageConv.GenerateImage(html, "Png"); piccaptcha.Image = ByteArrayToImage(jpegBytes); Bitmap bitmapImage = new Bitmap(piccaptcha.Image); var ms = new MemoryStream(); Image image = piccaptcha.Image; image.Save(ms, ImageFormat.Png); var bytes = ms.ToArray(); var imageMemoryStream = new MemoryStream(bytes); Image imgFromStream = Image.FromStream(imageMemoryStream); imgFromStream.Save("captcha.jpg", ImageFormat.Jpeg); DebugHelper.VerboseMode = true; var api = new ImageToText { ClientKey = "ef85f1b1baa494a70b68cf1212727dcd", FilePath = "captcha.jpg" }; if (!api.CreateTask()) { DebugHelper.Out("API v2 send failed. " + api.ErrorMessage, DebugHelper.Type.Error); } else if (!api.WaitForResult()) { DebugHelper.Out("Could not solve the captcha.", DebugHelper.Type.Error); } else { DebugHelper.Out("Result: " + api.GetTaskSolution().Text, DebugHelper.Type.Success); captcha = api.GetTaskSolution().Text; txtcaptcha.Text = captcha; } }
protected void Page_Load(object sender, EventArgs e) { //IImageToText imageToText = new Tesseract(); IImageToText imageToText = new ImageToText(); string imgpath = Server.MapPath("/upload/10.jpg"); // text = imageToText.Transformation(imgpath, OcrType.Baidu); OcrType ocrType = OcrType.Baidu; if (!string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["OCR_TYPE"])) { ocrType = (OcrType)int.Parse(System.Configuration.ConfigurationManager.AppSettings["OCR_TYPE"]); } text = imageToText.Transformation(imgpath, ocrType); }
public async Task TestOCRFromMordor() { var apiKey = System.Environment.GetEnvironmentVariable("VISION_API_KEY"); Assert.IsFalse(string.IsNullOrWhiteSpace(apiKey), "Must provide API Key"); var imageToText = new ImageToText(apiKey); var mordorImage = "http://i.imgur.com/5ocZvsW.jpg"; var mordorTxt = new[] { "ONE DOES NOT", "SIMPLY", "OCR SOME TEXT FROM AN", "IMAGE" }; var result = await imageToText.ProcessImageToTextAsync(await ImageUtilities.SingleChannelAsync(new Uri(mordorImage), ImageUtilities.Channel.Blue)); var lines = ImageToText.ExtractLinesFromResponse(result).ToList(); lines.RemoveAt(lines.Count - 1); // Remove memegenerator.net line CollectionAssert.AreEqual(mordorTxt, lines, "[{0}] != [{1}]", string.Join(",", mordorTxt), string.Join(",", lines)); }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Charset = "utf-8"; HttpPostedFile file = context.Request.Files["file"]; string folder = context.Request["path"], id = context.Request["id"], value = context.Request["id"]; string uploadPath = HttpContext.Current.Server.MapPath(folder) + "\\"; if (file != null) { if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } String fileName = file.FileName.Substring(file.FileName.LastIndexOf("\\") + 1, file.FileName.Length - 1 - file.FileName.LastIndexOf("\\")); ///取到当前时间的年、月、日、分、秒和毫秒的值,并使用字符串格式把它们组合成一个字符串 // String fileTime = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() // + DateTime.Now.Second.ToString() + DateTime.Now.Minute.ToString() // + DateTime.Now.Millisecond.ToString(); // String src = file.FileName.Substring(file.FileName.LastIndexOf(".") + 1, file.FileName.Length - file.FileName.LastIndexOf(".") - 1).ToLower(); //string fileName = fileTime + "." + src; file.SaveAs(uploadPath + fileName); string text = ""; try { IImageToText imageToText = new ImageToText(); OcrType ocrType = OcrType.Baidu; if (!string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["OCR_TYPE"])) { ocrType = (OcrType)int.Parse(System.Configuration.ConfigurationManager.AppSettings["OCR_TYPE"]); } text = imageToText.Transformation(uploadPath + fileName, ocrType); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } //下面这句代码缺少的话,上传成功后上传队列的显示不会自动消失 context.Response.Write("{ \"id\": \"" + id + "\", \"status\": true, \"message\": \"上传成功!\", \"value\": \"" + fileName + "\", \"text\": \"" + Until.string2Json(text) + "\" }"); } else { context.Response.Write("{ \"id\": null, \"status\": false, \"message\"上传失败!\", \"value\": null, \"text\": null }"); } }
private double?GetAntigateBalance() { if (sender_antigate is null) { System.Windows.MessageBox.Show("Значение ключа Antigate не было введено! "); return(null); } System.Windows.Controls.TextBox textbox = (System.Windows.Controls.TextBox)sender_antigate; var api = new ImageToText { ClientKey = textbox.Text }; var balance = api.GetBalance(); return(balance); }
private void checkapi() { string resultBalance = ""; try { if (captchaService == CaptchaService._2captcha) { _2Captcha _2Captcha = new _2Captcha(txtapikey.Text); resultBalance = _2Captcha.CheckBalance(); } else if (captchaService == CaptchaService.capmonter) { resultBalance = new CapMonsterCloud.CapMonsterClient(txtapikey.Text).GetBalanceAsync().Result.ToString(); } else { var api = new ImageToText { ClientKey = txtapikey.Text }; var balance = api.GetBalance(); if (balance == null) { //DebugHelper.Out("GetBalance() failed. " + api.ErrorMessage, DebugHelper.Type.Error); resultBalance = "ERROR_KEY"; } else { resultBalance = balance.ToString(); } } } catch (Exception ex) { File.AppendAllText("error_main_form.txt", ex.ToString() + "\r\n"); resultBalance = ex.Message; //MessageBox.Show(ex.Message + "\r\n" + ex.ToString()); } finally { lbbalan.Text = resultBalance + " $"; } }
public double getBalance() { double balance = 0; ImageToText api = new ImageToText { ClientKey = this.apiKey }; double?tmpBala = api.GetBalance(); if (tmpBala != null) { balance = double.Parse(tmpBala.ToString()); } return(balance); }
public async Task TestOCRFromMorpheus() { var apiKey = System.Environment.GetEnvironmentVariable("VISION_API_KEY"); Assert.IsFalse(string.IsNullOrWhiteSpace(apiKey), "Must provide API Key"); var imageToText = new ImageToText(apiKey); var morpheusImage = "http://i.imgur.com/1wL61Ro.jpg"; var morpheusText = new[] { "WHAT IF I TOLD", "YOU", "IT WAS STARING YOU RIGHT IN", "THE FACE?" }; var result = await imageToText.ProcessImageToTextAsync(await ImageUtilities.GammaAsync(new Uri(morpheusImage), 2.5)); var lines = ImageToText.ExtractLinesFromResponse(result).ToList(); Assert.IsTrue(lines.Any()); lines.RemoveAt(lines.Count - 1); // Remove memegenerator.net line CollectionAssert.AreEqual(morpheusText, lines, "[{0}] != [{1}]", string.Join(",", morpheusText), string.Join(",", lines)); }
public async Task TestOCRFromRx() { var apiKey = System.Environment.GetEnvironmentVariable("VISION_API_KEY"); Assert.IsFalse(string.IsNullOrWhiteSpace(apiKey), "Must provide API Key"); var imageToText = new ImageToText(apiKey); var rxFile = @"c:\dev\rximage.png"; var annotated = @"c:\dev\rximage_annotated.png"; var ocr = await imageToText.ProcessImageFileToTextAsync(rxFile); using (Stream inStream = new FileStream(rxFile, FileMode.Open, FileAccess.Read), annotatedStream = ImageUtilities.AnnotateImageWithOcrResults(inStream, ocr), outStream = new FileStream(annotated, FileMode.OpenOrCreate, FileAccess.Write)) { await annotatedStream.CopyToAsync(outStream); } }
private static void ExampleGetBalance() { DebugHelper.VerboseMode = true; var api = new ImageToText { ClientKey = "1234567890123456789012" }; var balance = api.GetBalance(); if (balance == null) { DebugHelper.Out("GetBalance() failed. " + api.ErrorMessage, DebugHelper.Type.Error); } else { DebugHelper.Out("Balance: " + balance, DebugHelper.Type.Success); } }
private static void ExampleGetBalance() { DebugHelper.VerboseMode = true; var api = new ImageToText { ClientKey = "d80651cde66496a42a548e9dde92ac32" }; var balance = api.GetBalance(); if (balance == null) { DebugHelper.Out("GetBalance() failed. " + api.ErrorMessage ?? "", DebugHelper.Type.Error); } else { DebugHelper.Out("Balance: " + balance, DebugHelper.Type.Success); } }
public static void ExampleGetBalance() { DebugHelper.VerboseMode = true; var api = new ImageToText { ClientKey = "9ec539ed2708163fedbceb896bb1ba5f" }; var balance = api.GetBalance(); if (balance == null) { DebugHelper.Out("GetBalance() failed. " + api.ErrorMessage ?? "", DebugHelper.Type.Error); } else { DebugHelper.Out("Balance: " + balance, DebugHelper.Type.Success); } }
private static void ExampleImageToText() { DebugHelper.VerboseMode = true; var api = new ImageToText { ClientKey = "1234567890123456789012", FilePath = "captcha.jpg" }; if (!api.CreateTask()) { DebugHelper.Out("API v2 send failed. " + api.ErrorMessage ?? "", DebugHelper.Type.Error); } else if (!api.WaitForResult()) { DebugHelper.Out("Could not solve the captcha.", DebugHelper.Type.Error); } else { DebugHelper.Out("Result: " + api.GetTaskSolution(), DebugHelper.Type.Success); } }
/// <summary> /// Main method Entry point /// </summary> /// <param name="args">parameter to process the input image</param> private static void Main(string[] args) { // in(i) out(o) reverse(r) var param = new List<string> { "/i", "/o", "/r", "/h", "/w" }; // i o r must be at odd position // -- /i is must if (args.Count(c => c == "/i" || c == "/I") == 0) { Console.WriteLine( "\t>>Please check the command format.\n\tCommand it not properly formatted.\n\t'/i file.jpg' is required."); ShowHelp(); return; } if (param.Any(c => { var index = Array.FindIndex(args, el => el.Equals(c, StringComparison.InvariantCultureIgnoreCase)); return index > -1 && index % 2 == 1; })) { Console.WriteLine("\t>>Please check the command format.\n\tCommand it not properly formatted."); ShowHelp(); return; } Func<string, string> myFunc = ope => { var index = Array.FindIndex(args, el => el.Equals(ope, StringComparison.InvariantCultureIgnoreCase)); if (index > -1 && index + 1 < args.Length) { return args[index + 1]; } return string.Empty; }; Func<string, int> getPercentageValue = ope => { var result = -1; var value = myFunc(ope); if (!string.IsNullOrEmpty(value)) { if (value.Last() == '%') { value = value.Substring(0, value.Length - 1).Trim(); } int.TryParse(value, out result); if (result > 100) { result = 100; } } return result; }; var filePassedIn = myFunc(param.ElementAt(0)); var outputFile = myFunc(param.ElementAt(1)); var isReverse = myFunc(param.ElementAt(2)).Equals("1"); var height = getPercentageValue(param.ElementAt(3)); var width = getPercentageValue(param.ElementAt(4)); filePassedIn = GetTheFilePath(filePassedIn); outputFile = string.IsNullOrEmpty(outputFile) ? Path.GetFileNameWithoutExtension(filePassedIn) + ".txt" : outputFile; if (string.IsNullOrEmpty(filePassedIn)) { return; } var obj = new ImageToText(filePassedIn); obj.Reverse = isReverse; Console.WriteLine("Converting from [{0}] to [{1}]...", Path.GetFileName(filePassedIn), outputFile); Thread.Sleep(500); if (obj.SaveTheLoad(outputFile, width, height)) { Console.WriteLine("File Processed successfully."); } Thread.Sleep(200); }
private bool CreateImageConverter(string imagePath, bool useCurrentSettings) { // Create/Get ASCII Art Converter. try { AsciiArtist = new ImageToText(imagePath); } catch (FileNotFoundException) { MessageBox.Show("Cannot find image file at: " + txtImageFile.Text, "Error"); return(false); } catch (Exception exc) { MessageBox.Show(exc.Message, "Error"); return(false); } // Configuration settings of ASCII Art Converter. if (useCurrentSettings) { // Set ASCII characters to use for ASCII art AsciiArtist.UseAlpabets = chkUseAlpha.Checked; AsciiArtist.UseNumbers = chkUseNum.Checked; AsciiArtist.UseBasicSymbols = chkUseBasic.Checked; AsciiArtist.UseExtendedSymbols = chkUseExtended.Checked; AsciiArtist.UseBlockSymbols = chkUseBlock.Checked; AsciiArtist.UseFixedChars = chkUseFixed.Checked; AsciiArtist.FixedChars = txtFixedChars.Text.ToCharArray(); // Set ASCII text font size try { if (txtFontSize.SelectedItem != null) { AsciiArtist.FontSize = (int)UInt16.Parse(txtFontSize.SelectedItem.ToString()); } else { //default font size = 6 pt AsciiArtist.FontSize = (int)UInt16.Parse("6"); } } catch { MessageBox.Show("Invalid font size! Reset to default value.", "Error"); } // Set Background color (HTML ASCII art only) if (txtBackColor.SelectedItem != null) { AsciiArtist.BackColor = txtBackColor.SelectedItem.ToString(); } else { //default background color AsciiArtist.BackColor = "White"; } // Set Foreground or text color (HTML ASCII art only) if (txtForeColor.SelectedItem != null) { AsciiArtist.FontColor = txtForeColor.SelectedItem.ToString(); } else { //default foreground or text color AsciiArtist.FontColor = "Black"; } // Set color gradient AsciiArtist.UseColors = radMultiColor.Checked; AsciiArtist.IsGrayScale = chkGrayScale.Checked; if (chkGrayScale.Checked) { //Grayscale = use more than 1 color or use gradient AsciiArtist.UseColors = true; } // Set ASCII text output as HTML or text AsciiArtist.IsHtmlOutput = !chkTextOnly.Checked; } return(true); }
private async void btnIniciarConsulta_Click(object sender, EventArgs e) { do { //foreach (var consul in layout) //{ wb.Document.GetElementById("aceiteTermoUso").SetAttribute("checked", "true"); if (!string.IsNullOrEmpty(layout[totalconsultado].CPFCNPJ)) { txtcpf.Text = layout[totalconsultado].CPFCNPJ; wb.Document.GetElementById("cpfCnpjEmitente").InnerText = txtcpf.Text; } if (!string.IsNullOrEmpty(layout[totalconsultado].CM7D1)) { txtd1.Text = layout[totalconsultado].CM7D1; wb.Document.GetElementById("primeiroCampoCmc7").InnerText = txtd1.Text; } if (!string.IsNullOrEmpty(layout[totalconsultado].CM7D2)) { txtd2.Text = layout[totalconsultado].CM7D2; wb.Document.GetElementById("segundoCampoCmc7").InnerText = txtd2.Text; } if (!string.IsNullOrEmpty(layout[totalconsultado].CM7D3)) { txtd3.Text = layout[totalconsultado].CM7D3; wb.Document.GetElementById("terceiroCampoCmc7").InnerText = txtd3.Text; } if (!string.IsNullOrEmpty(layout[totalconsultado].CPFINTERESSADO)) { txtcpfinteressado.Text = layout[totalconsultado].CPFINTERESSADO; wb.Document.GetElementById("cpfCnpjInteressado").InnerText = txtcpfinteressado.Text; } var text = wb.Document.GetElementById("cipCaptchaImg"); var html = String.Format("{0}{1}{2}", "<table cellpadding=\"0\" cellspacing=\"0\">", text.InnerHtml, "</table>"); var htmlToImageConv = new NReco.ImageGenerator.HtmlToImageConverter(); // htmlToImageConv.Height = 70; htmlToImageConv.Width = 200; var jpegBytes = htmlToImageConv.GenerateImage(html, "Png"); piccaptcha.Image = ByteArrayToImage(jpegBytes); Bitmap bitmapImage = new Bitmap(piccaptcha.Image); var ms = new MemoryStream(); Image image = piccaptcha.Image; image.Save(ms, ImageFormat.Png); var bytes = ms.ToArray(); var imageMemoryStream = new MemoryStream(bytes); Image imgFromStream = Image.FromStream(imageMemoryStream); imgFromStream.Save("captcha.jpg", ImageFormat.Jpeg); DebugHelper.VerboseMode = true; var api = new ImageToText { ClientKey = "ef85f1b1baa494a70b68cf1212727dcd", FilePath = "captcha.jpg" }; if (!api.CreateTask()) { DebugHelper.Out("API v2 send failed. " + api.ErrorMessage, DebugHelper.Type.Error); } else if (!api.WaitForResult()) { DebugHelper.Out("Could not solve the captcha.", DebugHelper.Type.Error); } else { DebugHelper.Out("Result: " + api.GetTaskSolution().Text, DebugHelper.Type.Success); captcha = api.GetTaskSolution().Text; txtcaptcha.Text = captcha; } if (!string.IsNullOrEmpty(captcha)) { wb.Document.GetElementById("captcha").InnerText = captcha; } //status.Text = "Aguardar 3 segundos"; //Thread.Sleep(3000); wb.Document.GetElementById("btEnviar").InvokeMember("click"); //Thread.Sleep(5000); var item = wb.Document.GetElementById("errors"); if (item.InnerHtml != null) { if ((item.InnerText.Contains(@"Código da Imagem: Caracteres do captcha não foram preenchidos corretamente ou o tempo máximo para preenchimento foi ultrapassado")) || (item.InnerText.Contains(@"Código da Imagem é um campo obrigatório"))) { //MessageBox.Show(@"Código da Imagem: Caracteres do captcha não foram preenchidos corretamente ou o tempo máximo para preenchimento foi ultrapassado"); status.Text = @"Código da Imagem: Caracteres do captcha não foram preenchidos corretamente ou o tempo máximo para preenchimento foi ultrapassado"; //goto repete; } } atualizaConsultado(); } while (totalconsultado < totalConsulta); //} }
private async void btnConsultar_Click(object sender, EventArgs e) { wb.Document.GetElementById("aceiteTermoUso").SetAttribute("checked", "true"); if (!string.IsNullOrEmpty(txtcpf.Text)) { wb.Document.GetElementById("cpfCnpjEmitente").InnerText = txtcpf.Text.Trim(); } if (!string.IsNullOrEmpty(txtd1.Text)) { wb.Document.GetElementById("primeiroCampoCmc7").InnerText = txtd1.Text.Trim(); } if (!string.IsNullOrEmpty(txtd2.Text)) { wb.Document.GetElementById("segundoCampoCmc7").InnerText = txtd2.Text.Trim(); } if (!string.IsNullOrEmpty(txtd3.Text)) { wb.Document.GetElementById("terceiroCampoCmc7").InnerText = txtd3.Text.Trim(); } if (!string.IsNullOrEmpty(txtcpfinteressado.Text)) { wb.Document.GetElementById("cpfCnpjInteressado").InnerText = txtcpfinteressado.Text.Trim(); } var text = wb.Document.GetElementById("cipCaptchaImg"); var html = String.Format("{0}{1}{2}", "<table cellpadding=\"0\" cellspacing=\"0\">", text.InnerHtml, "</table>"); var htmlToImageConv = new NReco.ImageGenerator.HtmlToImageConverter(); // htmlToImageConv.Height = 70; htmlToImageConv.Width = 200; var jpegBytes = htmlToImageConv.GenerateImage(html, "Png"); piccaptcha.Image = ByteArrayToImage(jpegBytes); Bitmap bitmapImage = new Bitmap(piccaptcha.Image); var ms = new MemoryStream(); Image image = piccaptcha.Image; image.Save(ms, ImageFormat.Png); var bytes = ms.ToArray(); var imageMemoryStream = new MemoryStream(bytes); Image imgFromStream = Image.FromStream(imageMemoryStream); imgFromStream.Save("captcha.jpg", ImageFormat.Jpeg); DebugHelper.VerboseMode = true; var api = new ImageToText { ClientKey = "ef85f1b1baa494a70b68cf1212727dcd", FilePath = "captcha.jpg" }; if (!api.CreateTask()) { DebugHelper.Out("API v2 send failed. " + api.ErrorMessage, DebugHelper.Type.Error); } else if (!api.WaitForResult()) { DebugHelper.Out("Could not solve the captcha.", DebugHelper.Type.Error); } else { DebugHelper.Out("Result: " + api.GetTaskSolution().Text, DebugHelper.Type.Success); wb.Document.GetElementById("captcha").InnerText = api.GetTaskSolution().Text; txtcaptcha.Text = api.GetTaskSolution().Text; } if (!string.IsNullOrEmpty(txtcaptcha.Text)) { wb.Document.GetElementById("captcha").InnerText = txtcaptcha.Text.Trim(); } wb.Document.GetElementById("btEnviar").InvokeMember("click"); }
/// <summary> /// Решение обычной капчи с текстом /// </summary> /// <param name="imageToText">Модель данных</param> /// <param name="sleep">Задержка получения ответа</param> /// <returns></returns> public TaskResultResp ImageToText(ImageToText imageToText, int sleep = 3000) { var create = CreateTask(new CreateTask(imageToText)); return(GetResult(create, sleep)); }
private void TextTest_Click(object sender, RoutedEventArgs e) { ImageToText.HomeBoss(); }
public void VkAuth(string login, string password) { if (sender_Group_ID is null) { System.Windows.MessageBox.Show("Значение Group ID не было введено! "); return; } System.Windows.Controls.TextBox textbox = (System.Windows.Controls.TextBox)sender_Group_ID; GroupID = Convert.ToInt64(textbox.Text); Func <string> code = () => { string value = Microsoft.VisualBasic.Interaction.InputBox("Please enter code:", "Code Request", "Enter code there"); //MessageBox.Show(value); return(value); }; ulong appID = 2890984; // Используем официальное приложение VK для получения access token var vk = new VkApi(); long captchaSid = 0; string captchaAnswer = ""; long getuserid = 0; try { try { if (TwoFactorAuthorization == true) { vk.Authorize(new VkNet.Model.ApiAuthParams { ApplicationId = appID, Login = login, Password = password, Settings = Settings.All, TwoFactorAuthorization = code, CaptchaKey = captchaAnswer, CaptchaSid = captchaSid } ); } else { vk.Authorize(new VkNet.Model.ApiAuthParams { ApplicationId = appID, Login = login, Password = password, Settings = Settings.All, CaptchaKey = captchaAnswer, CaptchaSid = captchaSid } ); } } catch (VkNet.Exception.VkApiException) { UnsuccessfulLogin++; System.Windows.MessageBox.Show("Неуспешная авторизация!"); return; } /* * catch (System.InvalidOperationException) * System.Windows.MessageBox.Show("Эта операция не поддерживается для относительных URI-адресов."); */ try { SuccessfulLogin++; var users = vk.Friends.Get(new VkNet.Model.RequestParams.FriendsGetParams { }); List <VkNet.Model.User> IDs = users.ToList(); foreach (VkNet.Model.User id in IDs) { getuserid = id.Id; vk.Groups.Invite(GroupID, id.Id); SuccessfulInvitesCount++; //System.Threading.Thread.Sleep(5000); //System.Windows.MessageBox.Show(Convert.ToString(id.Id)); } } catch (VkNet.Exception.AccessDeniedException e) { System.Windows.MessageBox.Show("Access denied: "); UnsuccessfulInvitesCount++; SuccessfulInvitesCount--; } catch (VkNet.Exception.CannotBlacklistYourselfException e) { System.Windows.MessageBox.Show("Access denied: user should be friend"); UnsuccessfulInvitesCount++; SuccessfulInvitesCount--; } } catch (VkNet.Exception.CaptchaNeededException cap) { captchaSid = cap.Sid; if (sender_antigate is null) { System.Windows.MessageBox.Show("Значение ключа Antigate не было введено! Не возможно отправить капчу на Antigate! "); return; } if (GetAntigateBalance() == 0) { System.Windows.MessageBox.Show("Нет средств на балансе Antigate"); return; } System.Windows.Controls.TextBox textbox2 = (System.Windows.Controls.TextBox)sender_antigate; var api = new ImageToText { ClientKey = textbox2.Text, FilePath = cap.Img.ToString() }; if (!api.CreateTask()) { System.Windows.MessageBox.Show("API v2 send failed. " + api.ErrorMessage); UnsuccessfulCaptcha++; } else if (!api.WaitForResult()) { System.Windows.MessageBox.Show("Could not solve the captcha."); UnsuccessfulCaptcha++; } else { //System.Windows.MessageBox.Show("Result: " + api.GetTaskSolution().Text); captchaAnswer = api.GetTaskSolution().Text; SuccessfulCaptcha++; vk.Groups.Invite(GroupID, getuserid, captchaSid, captchaAnswer); } } }