public List <string> RecognizeText(Stream bitmap) { List <string> list = new List <string>(); try { OCR ocr = visionServiceClient.RecognizeText(bitmap, LanguageCodes.AutoDetect, true); string result = new Gson().ToJson(ocr); OCRModel ocrModel = JsonConvert.DeserializeObject <OCRModel>(result); foreach (var region in ocrModel.regions) { foreach (var line in region.lines) { foreach (var word in line.words) { list.Add(word.text); } } } } catch (Java.Lang.Exception ex) { ex.PrintStackTrace(); string b = ""; } return(list); }
public void cropImage_ConvertMulti(List <OCRModel.Position> CropPos, List <string> imagePath, string name, List <int> formID, int totalpage) { OCRModel imgpath = new OCRModel(); OCRModel obj = new OCRModel(); var CropRes = new List <OCRModel.CropResult>(); int i = 0; string croppath = ""; Bitmap croppedImage; for (int j = 1; j <= totalpage; j++) { i = 0; for (i = 0; i < CropPos.Count; i++) { if (j == CropPos[i].page) { j--; // Here we capture the resource - image file. using (var originalImage = new Bitmap(imagePath[j])) { //Set Position {x1,y1,width,height} Rectangle crop = new Rectangle(CropPos[i].pos_X1, CropPos[i].pos_Y1, CropPos[i].pos_width, CropPos[i].pos_height); // Here we capture another resource. croppedImage = originalImage.Clone(crop, originalImage.PixelFormat); }// Here we release the original resource - bitmap in memory and file on disk. // At this point the file on disk already free - you can record to the same path. //croppedImage.Save(@"C:\Users\kazarboys\Source\Repos\How-to-use-tesseract-ocr-4.0-with-csharp\tesseract-master.1153\samples\crop.jpg", ImageFormat.Jpeg); croppath = Path.Combine(Server.MapPath("~/Images/Crop"), name + "" + formID[j] + "_crop_" + i + ".jpg"); croppedImage.Save(croppath, ImageFormat.Jpeg); var Ocr = new AutoOcr(); var OcrResult = Ocr.Read(croppath); Console.WriteLine(OcrResult.Text); //string Crop_Text = OcrResult.Text.Replace("\r\n", "\\r\\n"); CropRes.Add(new OCRModel.CropResult { FormID_Key = formID[j], Crop_Imgpath = croppath.ToString(), Crop_Text = OcrResult.ToString().Replace("\r\n", "\\r\\n") }); // It is desirable release this resource too. croppedImage.Dispose(); j++; } } } //Insert CropImage to DB imgpath.InsertCropResult(CropRes); }
public ActionResult AssignCheck(int id) { OCRModel ocrModel = new OCRModel(); try { ocrModel = Mapper.Map <OCRModel>(_ocr.GetOCRDetailById(id)); ocrModel.OcrFilePath = Path.Combine(ConfigurationManager.AppSettings[GlobalConst.ConstantChar.StoragePath].ToString(), GlobalConst.ConstantChar.OCRUploads, ocrModel.OcrFileName); } catch (Exception ex) { _arCommonService.CreateErrorLog(ex.Message, ex.StackTrace); } return(View(ocrModel)); }
public ActionResult AddOCRPaymentRecords(IEnumerable <OCRPaymentSave> objOCRPaymentSave) { try { var result = 0; var ocrID = 0; if (objOCRPaymentSave != null) { var objOCRpaymentList = objOCRPaymentSave.ToList(); foreach (var objocrPaymentSaveModel in objOCRpaymentList) { if (result == 0) { ocrID = objocrPaymentSaveModel.OCRId; } objocrPaymentSaveModel.OCRId = ocrID; objocrPaymentSaveModel.CreatedBy = Convert.ToInt32(Request.Cookies[GlobalConst.SessionKeys.userDetailMgmt].Values[GlobalConst.SessionKeys.userID]); OCRPayment ObjOCRPayment = new OCRPayment(); int _PaymentId = _ocr.AddOCRPaymentRecords(Mapper.Map <LMGEDI.Core.Data.Model.OCRPaymentSave>(objocrPaymentSaveModel)).PaymentId; _storageServices.CreatePaymentCheckFolder(objocrPaymentSaveModel.FileID, objocrPaymentSaveModel.InvoiceID, _PaymentId, Server.MapPath(ConfigurationManager.AppSettings[GlobalConst.ConstantChar.StoragePath])); System.IO.File.Copy(Server.MapPath(ConfigurationManager.AppSettings[GlobalConst.ConstantChar.StoragePath].ToString()) + GlobalConst.ConstantChar.DoubleSlash + GlobalConst.ConstantChar.OCRUploads + GlobalConst.ConstantChar.DoubleSlash + objocrPaymentSaveModel.CheckUploadName, Path.Combine(Server.MapPath(ConfigurationManager.AppSettings[GlobalConst.ConstantChar.StoragePath]), objocrPaymentSaveModel.FileID.ToString(), objocrPaymentSaveModel.InvoiceID.ToString(), _PaymentId.ToString(), objocrPaymentSaveModel.CheckUploadName), true); if (result == 0) { OCRModel ocrModel = new OCRModel(); ocrModel = Mapper.Map <OCRModel>(_ocr.GetOCRDetailById(ocrID)); ocrModel.IsOCRPaymentRecevied = true; int OCRUpdated = _ocr.UpdateOCRRecord(Mapper.Map <LMGEDI.Core.Data.Model.OCR>(ocrModel)); } result = 1; } } else { result = 2; } return(Json(result)); } catch (Exception ex) { _arCommonService.CreateErrorLog(ex.Message, ex.StackTrace); return(Json(GlobalConst.ObjectTypes.Error)); } }
public async Task <string> MakeOCRRequest(Stream imageFilePath, string visionApiKey) { var client = new HttpClient(); // Request headers client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", visionApiKey); // Request parameters and URI string requestParameters = "language=unk&detectOrientation =true"; string uri = "https://westus.api.cognitive.microsoft.com/vision/v1.0/ocr?" + requestParameters; HttpResponseMessage response; // Request body. Try this sample with a locally stored JPEG image. byte[] byteData = ReadFully(imageFilePath); using (var content = new ByteArrayContent(byteData)) { // This example uses content type "application/octet-stream". // The other content types you can use are "application/json" and "multipart/form-data". content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); response = await client.PostAsync(uri, content); var resultContent = await response.Content.ReadAsStringAsync(); OCRModel result = JsonConvert.DeserializeObject <OCRModel>(resultContent); StringBuilder stringResult = new StringBuilder(); for (int i = 0; i < result.Regions.Count; i++) { for (int y = 0; y < result.Regions[i].Lines.Count; y++) { for (int z = 0; z < result.Regions[i].Lines[y].Words.Count; z++) { stringResult.Append(result.Regions[i].Lines[y].Words[z].Text); stringResult.Append(" "); } } } return(stringResult.ToString());; } }
protected override void OnPostExecute(string result) { mDialog.Dismiss(); OCRModel ocrModel = JsonConvert.DeserializeObject <OCRModel>(result); TextView txtDes = mainActivity.FindViewById <TextView>(Resource.Id.txtDescription); StringBuilder strBuilder = new StringBuilder(); foreach (var region in ocrModel.regions) { foreach (var line in region.lines) { foreach (var word in line.words) { strBuilder.Append(word.text + " "); } strBuilder.Append("\n"); } strBuilder.Append("\n\n"); } txtDes.Text = strBuilder.ToString(); }
public ActionResult UploadOCRFile(HttpPostedFileBase uploadOCRFile) { string result = GlobalConst.ConstantChar.Blank; try { OCRModel ocrModel = new OCRModel(); HttpPostedFileBase File = Request.Files[GlobalConst.ConstantChar.UploadOCRFile]; bool r = _storageServices.CreateOCRUploadFolder(Server.MapPath(ConfigurationManager.AppSettings[GlobalConst.ConstantChar.StoragePath]), GlobalConst.ConstantChar.OCRUploads); string OCRPath = Server.MapPath(ConfigurationManager.AppSettings[GlobalConst.ConstantChar.StoragePath].ToString()) + GlobalConst.ConstantChar.DoubleSlash + GlobalConst.ConstantChar.OCRUploads + GlobalConst.ConstantChar.DoubleSlash; string OCRFilePath = OCRPath + Path.GetFileName(uploadOCRFile.FileName); File.SaveAs(OCRFilePath); Reader bc = new Reader(); bc.RegistrationKey = WebConfigurationManager.AppSettings[GlobalConst.ConstantChar.BarCodeKey]; bc.RegistrationName = WebConfigurationManager.AppSettings[GlobalConst.ConstantChar.BarCodeKeyName]; bc.BarcodeTypesToFind.Code39 = true; iTextSharp.text.pdf.PdfReader reader = null; reader = new iTextSharp.text.pdf.PdfReader(OCRFilePath); FoundBarcode[] barcodes = bc.ReadFrom(OCRFilePath).Where(val => val.Value == GlobalConst.ConstantChar.BarCodeCHECK).ToArray(); int i = 0; for (i = 0; i <= barcodes.Length - 1; i++) { string newOCRfileName = Guid.NewGuid().ToString() + GlobalConst.Extension.PDF; string newOCRfilepath = OCRPath + newOCRfileName; string[] barcodename1 = barcodes[i].Value.Split(GlobalConst.ConstantChar.RoundBracketStart); string barcodename = barcodename1[0]; int pagenoE = 0; int pagenoS = barcodes[i].Page; //page starting bool flag = false; if (i == barcodes.Length - 1) { pagenoE = reader.NumberOfPages; } else { int num = 1; while (flag == false) { if (i + num < barcodes.Length) { if (barcodename == GlobalConst.ConstantChar.BarCodeCHECK) { pagenoE = barcodes[i + num].Page; flag = true; } } else { flag = true; pagenoE = reader.NumberOfPages; } num = num + 1; } } if (barcodename == GlobalConst.ConstantChar.BarCodeCHECK) { ocrModel.OcrFileName = newOCRfileName; ocrModel.CreatedBy = Convert.ToInt32(Request.Cookies[GlobalConst.SessionKeys.userDetailMgmt].Values[GlobalConst.SessionKeys.userID]); ocrModel.CreatedOn = DateTime.Now; _ocr.AddOCRRecord(Mapper.Map <LMGEDI.Core.Data.Model.OCR>(ocrModel)); ExtractPage(OCRFilePath, newOCRfilepath, pagenoS + 1, pagenoE - 1); result = GlobalConst.ConstantChar.True; } } reader.Dispose(); System.IO.File.Delete(OCRFilePath); } catch (Exception ex) { _arCommonService.CreateErrorLog(ex.Message, ex.StackTrace); } return(Json(result)); }
public ActionResult UploadImg() { string path = ""; string fileName = ""; string convertpath = ""; string filenamenoext = ""; string fileext = ""; List <int> ResultFormID = new List <int>(); int DocID = 0; List <string> docpage = new List <string>(); int totalpageno = 0; DocID = Convert.ToInt32(Request.Form["DDlDoc"].ToString()); OCRModel imgpath = new OCRModel(); if (Request.Files.Count > 0) { var file = Request.Files[0]; if (file != null && file.ContentLength > 0) { filenamenoext = Path.GetFileNameWithoutExtension(file.FileName); fileName = Path.GetFileName(file.FileName); fileext = Path.GetExtension(file.FileName); path = Path.Combine(Server.MapPath("~/Images/"), fileName); //Save File to destination folder file.SaveAs(path); if (fileext == ".pdf") { //Get pdf total page number FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); StreamReader r = new StreamReader(fs); string pdfText = r.ReadToEnd(); Regex rx1 = new Regex(@"/Type\s*/Page[^s]"); MatchCollection matches = rx1.Matches(pdfText); totalpageno = matches.Count; for (int i = 1; i <= totalpageno; i++) { PdfToImage.PDFConvert pp = new PDFConvert(); pp.OutputFormat = "jpeg"; //format pp.JPEGQuality = 100; //100% quality pp.ResolutionX = 300; //dpi pp.ResolutionY = 300; pp.FirstPageToConvert = i; //pages you want pp.LastPageToConvert = 2; convertpath = Path.Combine(Server.MapPath("~/Images/"), "name_pg" + i + ".jpeg"); pp.Convert(path, convertpath); docpage.Add(convertpath); } } else { //Non Pdf file docpage.Add(path); } //Save sourcefile information to DB ResultFormID = imgpath.insertForm(docpage, DocID); } } if (ResultFormID.Count != 0) { OCRModel obj = new OCRModel(); var PosResult = new List <OCRModel.Position>(); //Get position for each box PosResult = imgpath.retrieveBoxPos(DocID); if (totalpageno == 0) { int passID = ResultFormID[0]; cropImage_Convert(PosResult, path, filenamenoext, passID); } else { //Crop Image base on position and convert to image cropImage_ConvertMulti(PosResult, docpage, filenamenoext, ResultFormID, totalpageno); } } else { } return(RedirectToAction("Upload")); }
public ActionResult FormDetail(string id) { OCRModel getDetailResult = new OCRModel(); return(View(getDetailResult.getDetailList(id))); }
public ActionResult FormListing() { OCRModel ListResult = new OCRModel(); return(View(ListResult.getListing())); }