private void TryAddFloater(ImageViewerItem item) { PDF417BarcodeData barcodeData = (PDF417BarcodeData)BarcodeData.CreateDefaultBarcodeData(BarcodeSymbology.PDF417); barcodeData.SetData(_data); _engine.Writer.CalculateBarcodeDataBounds(LeadRect.Empty, item.Image.XResolution, item.Image.YResolution, barcodeData, _writeOptions); if (barcodeData.Rect.Width <= item.Image.Width && barcodeData.Rect.Height <= item.Image.Height) { _bigEnoughForBarcode = true; this.ImageViewer.Cursor = System.Windows.Forms.Cursors.Default; RasterImage floaterImage = RasterImage.Create(barcodeData.Rect.Width, barcodeData.Rect.Height, 32, Math.Max(item.Image.XResolution, item.Image.YResolution), RasterColor.Create(0, 255, 255, 255)); _engine.Writer.WriteBarcode(floaterImage, barcodeData, _writeOptions); item.Floater = floaterImage; item.FloaterOpacity = 0.5; } else { this.ImageViewer.Cursor = System.Windows.Forms.Cursors.No; _bigEnoughForBarcode = false; } }
private RasterImage CreateAttachmentImage(ImageViewer imageViewer) { // Get the attachment image from the resource Bitmap icon = Properties.Resources.Attachment; using (RasterImage image = RasterImageConverter.ConvertFromImage(icon, ConvertFromImageOptions.None)) { // Resize the image to be the same as width as image viewer thumbnails with original height int desiredWidth; if (_documentViewer.Thumbnails != null) { desiredWidth = _documentViewer.Thumbnails.MaximumSize.Width; } else { desiredWidth = image.ImageWidth; } var destRect = new LeadRect(0, 0, desiredWidth, image.ImageHeight); RasterImage attachmentImage = RasterImage.Create(destRect.Width, destRect.Height, 32, 96, RasterColor.Black); new SetAlphaValuesCommand(0x00).Run(attachmentImage); LeadRect imageRect = RasterImage.CalculatePaintModeRectangle( image.ImageWidth, image.ImageHeight, destRect, RasterPaintSizeMode.Fit, RasterPaintAlignMode.Center, RasterPaintAlignMode.Center); new CombineFastCommand(attachmentImage, imageRect, LeadPoint.Empty, Leadtools.ImageProcessing.CombineFastCommandFlags.SourceCopy).Run(image); return(attachmentImage); } }
static void Main(string[] args) { String fileToConvert = @"FILE PATH HERE"; RasterSupport.SetLicense(@"C:\LEADTOOLS 20\Common\License\LEADTOOLS.LIC", System.IO.File.ReadAllText(@"C:\LEADTOOLS 20\Common\License\LEADTOOLS.LIC.KEY")); using (RasterCodecs codecs = new RasterCodecs()) { using (IOcrEngine ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD, false)) { ocrEngine.Startup(null, null, null, @"C:\LEADTOOLS 20\Bin\Common\OcrLEADRuntime"); using (IOcrPage ocrPage = ocrEngine.CreatePage(ocrEngine.RasterCodecsInstance.Load(fileToConvert, 1), OcrImageSharingMode.AutoDispose)) { ocrPage.AutoZone(null); ocrPage.Recognize(null); string recognizedCharacters = ocrPage.GetText(-1); BarcodeEngine engine = new BarcodeEngine(); int resolution = 300; using (RasterImage image = RasterImage.Create((int)(8.5 * resolution), (int)(11.0 * resolution), 1, resolution, RasterColor.FromKnownColor(RasterKnownColor.White))) { BarcodeWriter writer = engine.Writer; QRBarcodeData data = BarcodeData.CreateDefaultBarcodeData(BarcodeSymbology.QR) as QRBarcodeData; data.Bounds = new LeadRect(0, 0, image.ImageWidth, image.ImageHeight); QRBarcodeWriteOptions writeOptions = writer.GetDefaultOptions(data.Symbology) as QRBarcodeWriteOptions; writeOptions.XModule = 30; writeOptions.HorizontalAlignment = BarcodeAlignment.Near; writeOptions.VerticalAlignment = BarcodeAlignment.Near; data.Value = recognizedCharacters; writer.CalculateBarcodeDataBounds(new LeadRect(0, 0, image.ImageWidth, image.ImageHeight), image.XResolution, image.YResolution, data, writeOptions); Console.WriteLine("{0} by {1} pixels", data.Bounds.Width, data.Bounds.Height); writer.WriteBarcode(image, data, writeOptions); CropCommand cmd = new CropCommand(new LeadRect(0, 0, data.Bounds.Width, data.Bounds.Height)); cmd.Run(image); codecs.Save(image, "QR.tif", RasterImageFormat.CcittGroup4, 1); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var process = new Process(); process.StartInfo = new ProcessStartInfo("QR.tif") { UseShellExecute = true }; process.Start(); } Console.WriteLine(); } } } } }
//public static byte[] CreateBarcode( string value, int resolution, int Width, int Height, bool Save2File,bool usingMemory, ref string ErrMsg) //{ // byte[] arrImg; // BarcodeEngine barEngine; // try // { // RasterImage theImage = RasterImage.Create((int)(8.5 * resolution), (int)(11.0 * resolution), 1, resolution, RasterColor.FromKnownColor(RasterKnownColor.White)); // // Unlock barcode support. // // Note that this is a sample key, which will not work in your toolkit // BarcodeEngine.Startup(BarcodeMajorTypeFlags.Barcodes1d); // BarcodeEngine.Startup(BarcodeMajorTypeFlags.BarcodesPdfWrite); // BarcodeEngine.Startup(BarcodeMajorTypeFlags.BarcodesDatamatrixWrite); // BarcodeEngine.Startup(BarcodeMajorTypeFlags.BarcodesQrWrite); // // Initialize barcodes // barEngine = new BarcodeEngine(); // BarcodeData data = new BarcodeData(); // LeadRect rc = new LeadRect(0, 0, Width, Height); // data.Unit = BarcodeUnit.ScanlinesPerPixels; // data.Location = rc; // data.SearchType = BarcodeSearchTypeFlags.DatamatrixDefault; // string[] barcodeText; // barcodeText = new string[1]; // barcodeText[0] = value; // data.Data = BarcodeData.ConvertFromStringArray(barcodeText); // BarcodeColor barColor = new BarcodeColor(); // barColor.BarColor = RasterColor.FromKnownColor(RasterKnownColor.Black); // barColor.SpaceColor = RasterColor.FromKnownColor(RasterKnownColor.White); // Barcode1d bar1d = new Barcode1d(); // BarcodeWritePdf barPDF = new BarcodeWritePdf(); // BarcodeWriteDatamatrix barDM = new BarcodeWriteDatamatrix(); // bar1d.StandardFlags = Barcode1dStandardFlags.Barcode1dCode128EncodeA; // barDM.Justify = BarcodeJustifyFlags.Right; // barDM.FileIdHigh = 0; // barDM.FileIdLow = 0; // barDM.GroupNumber = 0; // barDM.GroupTotal = 0; // barDM.XModule = 0; // BarcodeWriteQr barQR = new BarcodeWriteQr(); // string barcodeFileName = AppDomain.CurrentDomain.BaseDirectory + @"\barcode.tif"; // barEngine.Write(theImage, data, barColor, BarcodeWriteFlags.UseColors | BarcodeWriteFlags.Transparent | BarcodeWriteFlags.DisableCompression, bar1d, barPDF, barDM, barQR, LeadRect.Empty); // if (usingMemory) // { // using (MemoryStream _stream = new MemoryStream()) // { // using (RasterCodecs _Codecs = new RasterCodecs()) // { // _Codecs.Save(theImage, _stream, RasterImageFormat.Tif, theImage.BitsPerPixel); // arrImg = _stream.ToArray(); // if (Save2File) // { // _Codecs.Save(theImage, barcodeFileName, RasterImageFormat.Tif, theImage.BitsPerPixel); // } // } // } // } // else // { // using (RasterCodecs _Codecs = new RasterCodecs()) // { // _Codecs.Save(theImage, barcodeFileName, RasterImageFormat.Tif, theImage.BitsPerPixel); // arrImg = System.IO.File.ReadAllBytes(barcodeFileName); // } // } // } // catch (Exception ex) // { // ErrMsg = ex.Message; // return null; // } // return arrImg; //} public static byte[] CreateBarcode(BarcodeSymbology _BarcodeSymbology, string value, int resolution, int Width, int Height, bool Save2File, bool usingMemory, ref string ErrMsg) { ErrMsg = ""; BarcodeEngine barcodeEngineInstance = new BarcodeEngine(); RasterImage theImage = RasterImage.Create((int)(8.5 * resolution), (int)(11.0 * resolution), 1, resolution, RasterColor.FromKnownColor(RasterKnownColor.White)); // Create a UPC A barcode BarcodeData data = new BarcodeData(); data.Symbology = _BarcodeSymbology; data.Value = value; data.Bounds = new LogicalRectangle(10, 10, Width, Height, LogicalUnit.Pixel); // Setup the options to enable error checking and show the text on the bottom of the barcode OneDBarcodeWriteOptions options = new OneDBarcodeWriteOptions(); options.EnableErrorCheck = true; options.TextPosition = BarcodeOutputTextPosition.None;// OneDBarcodeTextPosition.Default; byte[] arrImg; try { string barcodeFileName = AppDomain.CurrentDomain.BaseDirectory + @"\barcode.tif"; // Write the barcode barcodeEngineInstance.Writer.WriteBarcode(theImage, data, options); if (usingMemory) { using (MemoryStream _stream = new MemoryStream()) { using (RasterCodecs _Codecs = new RasterCodecs()) { _Codecs.Save(theImage, _stream, RasterImageFormat.Tif, theImage.BitsPerPixel); arrImg = _stream.ToArray(); if (Save2File) { _Codecs.Save(theImage, barcodeFileName, RasterImageFormat.Tif, theImage.BitsPerPixel); } } } } else { using (RasterCodecs _Codecs = new RasterCodecs()) { _Codecs.Save(theImage, barcodeFileName, RasterImageFormat.Tif, theImage.BitsPerPixel); arrImg = System.IO.File.ReadAllBytes(barcodeFileName); } } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); ErrMsg = ex.Message; return(null); } return(arrImg); }
private void WriteBarcodeForm_Load(object sender, System.EventArgs e) { // initialize the _viewer object _viewer = new ImageViewer(); _viewer.Dock = DockStyle.Fill; _viewer.BackColor = Color.DarkGray; Controls.Add(_viewer); _viewer.BringToFront(); // initialize the codecs object. _codecs = new RasterCodecs(); try { string imagePath = Path.Combine(DemosGlobal.ImagesFolder, "license_sample_rear_blank.png"); _viewer.Image = _codecs.Load(imagePath); } catch { _viewer.Image = RasterImage.Create(1100, 700, 24, 150, RasterColor.White); } _barcodeEngine = new BarcodeEngine(); _writeOptions = (PDF417BarcodeWriteOptions)_barcodeEngine.Writer.GetDefaultOptions(BarcodeSymbology.PDF417); //Refer to AAMVA CDS 2016 Section D.3 thru D.11.2 //Must range from 0.0066 to 0.015 inches _writeOptions.XModule = 15; //0.015 //Must >= 3 _writeOptions.XModuleAspectRatio = 3; //Error level must be at least 3, 5 is recommended _writeOptions.ECCLevel = PDF417BarcodeECCLevel.Level5; //Default WidthAspectRatio is 2:1. 4:1 looks similar to ID barcodes in the wild _writeOptions.SymbolWidthAspectRatio = 4; //Default quiet zone for PDF417 is 2 * XModule _viewer.BeginUpdate(); WriteBarcodeInteractiveMode writeBarcodeInteractiveMode = new WriteBarcodeInteractiveMode(_barcodeEngine, _aamvaData, _writeOptions); writeBarcodeInteractiveMode.IsEnabled = true; ImageViewerPanZoomInteractiveMode panZoomInteractiveMode = new ImageViewerPanZoomInteractiveMode(); _viewer.InteractiveModes.Add(writeBarcodeInteractiveMode); _viewer.InteractiveModes.Add(panZoomInteractiveMode); _viewer.EndUpdate(); UpdateMyControls(); }
public List <FilledForm> ProcessOcr(ResultsForPrettyJson formResults, List <ImageInfo> fileInfos) { try { var outDir = formResults.OriginalDirectoryName; var retForms = new List <FilledForm>(); var usedMasters = new HashSet <MasterForm>(); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); formResults.PagesInPdf = fileInfos.Count; foreach (var ofi in fileInfos) { FilledForm newForm = new FilledForm(); retForms.Add(newForm); newForm.ImageInfoMaster.InitialImage = ofi; newForm.Name = Path.GetFileNameWithoutExtension(ofi.ImageFileInfo.Name); if (ofi.Image == null) { ofi.Image = LoadImageFile(ofi.ImageFileInfo.FullName, 1, -1); } //CleanupImage(ofi.Image); var par = new FormThreadCallParams() { ImageInfo = ofi, StopWatch = stopWatch, Form = newForm }; if (PageTimeoutInSeconds < 50) { Thread t = new Thread(this.PrepareNewFormThreader); t.Start(par); if (!t.Join(TimeSpan.FromSeconds(PageTimeoutInSeconds))) { t.Abort(); formResults.TimedOutPages.Add(newForm.Name); formResults.BestFormConfidence.Add(-1); if (formResults.TimedOutPages.Count > 2 && formResults.PagesMappedToForm == 0) { formResults.Status = $"Form abandoned for timeout after {formResults.BestFormConfidence.Count} pages"; logger.Error(formResults.Status); return(retForms); } continue; } } else { PrepareNewFormThreader(par); } Debug.Assert(par.Attributes != null); var filledFormAttributes = par.Attributes; //List<FormRecognitionResult> results = new List<FormRecognitionResult>(); MasterForm currentMasterBlockForm = null; int bestConfidence = -1; int currentConfidence = 85; foreach (var master in BlockMasterForms) { if (usedMasters.Contains(master)) { continue; } var result = RecognitionEngine.CompareForm(master.Attributes, filledFormAttributes, null, null); //logger.Debug($"Check {master} for {newForm} {stopWatch.ElapsedMilliseconds} {result.Confidence}"); if (result.Confidence > currentConfidence) { currentMasterBlockForm = master; bestConfidence = currentConfidence = result.Confidence; } else if (result.Confidence > bestConfidence) { bestConfidence = result.Confidence; } } formResults.BestFormConfidence.Add(bestConfidence); if (currentMasterBlockForm != null) { formResults.MasterFormPages.Add(currentMasterBlockForm.Properties.Name); formResults.PagesMappedToForm++; logger.Info($"FilledForm matched {newForm.Name} {newForm.Status} {stopWatch.ElapsedMilliseconds} "); newForm.ImageInfoMaster.InitialImage = ofi; var centeredImage = ofi.Image.CloneAll(); CleanupImage(centeredImage); newForm.ImageInfoMaster.CenteredImage = new ImageInfo() { Image = centeredImage }; var omrImage = centeredImage.CloneAll(); PrepareOmrImage(omrImage); newForm.ImageInfoMaster.OmrImage = new ImageInfo() { Image = omrImage }; newForm.Status = "Matched"; newForm.Master = currentMasterBlockForm; var alignment = RecognitionEngine.GetFormAlignment(newForm.Master.Attributes, newForm.Attributes, null); var fields = currentMasterBlockForm.ProcessingPages[0]; var scaler = currentMasterBlockForm.Resolution; var fieldsOnlyImage = RasterImage.Create(centeredImage.Width, centeredImage.Height, centeredImage.BitsPerPixel, 300, RasterColor.White); //fieldsOnlyImage = new RasterImage(RasterMemoryFlags.Conventional, centeredImage.Width, centeredImage.Height, centeredInage.BitsPerPixel, RasterByteOrder.Rgb, RasterViewPerspective.TopLeft, null, null, 0); var subDirField = Path.Combine(outDir, "fields"); var fileNameFieldOnly = Path.Combine(subDirField, newForm.Name + "_fields.jpg"); var googleResultsFile = Path.Combine(subDirField, newForm.Name + "_google.json"); var combined = false; foreach (var field in fields) { var isBlock = field.Name.Contains("block"); var rect200 = alignment[0].AlignRectangle(field.Bounds); scaler = 300; int fudge = isBlock ? 30 : 1; var rect300 = new LeadRect(rect200.Left * 300 / scaler - fudge, rect200.Top * 300 / scaler - fudge, rect200.Width * 300 / scaler + fudge, rect200.Height * 300 / scaler + fudge); try { var imageInfoToUse = newForm.ImageInfoMaster.CenteredImage; var zoneType = OcrZoneType.Text; if (field.GetType() == typeof(OmrFormField)) { imageInfoToUse = newForm.ImageInfoMaster.OmrImage; zoneType = OcrZoneType.Omr; } else if (field.GetType() == typeof(ImageFormField)) { zoneType = OcrZoneType.Graphic; } var image = imageInfoToUse.Image.CloneAll(); var subDir = Path.Combine(outDir, isBlock ? "blocks" : "fields"); var fileName = Path.Combine(subDir, newForm.Name + "_" + field.Name + ".jpg"); var imageField = new ImageField { Field = field, FieldResult = { FieldName = field.Name, IsBlock = isBlock, ImageFile = fileName, Bounds = rect300.ToString(), FieldType = zoneType.ToString(), Error = "None" } }; imageField.Rectangle = new Rectangle(rect300.X, rect300.Y, rect300.Width, rect300.Height); try { EnsurePathExists(subDir); CropCommand command = new CropCommand { Rectangle = rect300 }; command.Run(image); RasterCodecs.Save(image, fileName, RasterImageFormat.Jpeg, bitsPerPixel: 8); if (!isBlock && zoneType == OcrZoneType.Text && !combined) { try { ; var combiner = new CombineCommand(); //combiner.DestinationImage = fieldsOnlyImage; combiner.SourceImage = image.Clone(); combiner.DestinationRectangle = rect300; var regionBounds = image.GetRegionBounds(null); combiner.SourcePoint = new LeadPoint(regionBounds.X, regionBounds.Y); //combiner.Flags = CombineCommandFlags.OperationAdd | CombineCommandFlags.Destination0 | CombineCommandFlags.Source1 | CombineCommandFlags.Destination0 ; combiner.Flags = CombineCommandFlags.OperationOr | CombineCommandFlags.Destination0;; // |CombineFastCommandFlags.OperationAverage; combiner.Run(fieldsOnlyImage); //combined = true; } catch (Exception exCombine) { logger.Error(exCombine, $"error combining field {field.Name} {rect300}"); } } var imageInfo = new ImageInfo() { Image = image, ImageFileInfo = new FileInfo(fileName) }; imageField.ImageInfo = imageInfo; if (!isBlock && zoneType != OcrZoneType.Graphic) { using (IOcrPage ocrPage = OcrEngine.CreatePage(image, OcrImageSharingMode.AutoDispose)) { OcrZone ocrZone = new OcrZone { ZoneType = zoneType, Bounds = new LeadRect(fudge, fudge, image.ImageSize.Width - fudge, image.ImageSize.Height - fudge) }; ocrPage.Zones.Add(ocrZone); ocrPage.Recognize(null); if (zoneType == OcrZoneType.Omr) { if (field.Name.Contains("C2NGVD1929")) { logger.Info(ocrZone.Bounds); } GetOmrReading(ocrPage, field, imageField); } else if (zoneType == OcrZoneType.Text) { var resultsPage = GetPageConfidence(ocrPage); imageField.FieldResult.Confidence = resultsPage.Confidence; char[] crlf = { '\r', '\n' }; imageField.FieldResult.Text = ocrPage.GetText(0).TrimEnd(crlf); } } } logger.Info( $"field {field.Name} {rect300} [{imageField.FieldResult.Text}] confidence: {imageField.FieldResult.Confidence}"); } catch (Exception exField) { logger.Error(exField, $"Error processing {field.Name}"); formResults.FieldsWithError++; imageField.FieldResult.Error = exField.Message; } newForm.ImageFields.Add(imageField); formResults.OcrFields.Add(imageField.FieldResult); formResults.Status = "FormMatched"; } catch (Exception ex) { logger.Error(ex, $"Error on field {field.Name} {rect300}"); newForm.Status = $"Error|Field {field.Name} {rect300}: [{ex.Message}]"; } } RasterCodecs.Save(PrepareOmrImage(fieldsOnlyImage), fileNameFieldOnly, RasterImageFormat.Jpeg, bitsPerPixel: 8); var googleResults = GoogleOcr(fileNameFieldOnly); if (googleResults.Count > 0) { var json = JsonConvert.SerializeObject(googleResults, Formatting.Indented); File.WriteAllText(googleResultsFile, json); MergeGoogleOcr(newForm, googleResults); } usedMasters.Add(currentMasterBlockForm); } else { newForm.Status = "Unmatched|No MasterForm match"; } logger.Info($"FilledForm processed {newForm.Name} {newForm.Status} {stopWatch.ElapsedMilliseconds} "); if (usedMasters.Count == BlockMasterForms.Count) { logger.Info("found all master forms"); break; } } stopWatch.Stop(); return(retForms); } catch (Exception ex) { logger.Error(ex, "Untrapped error found"); return(null); } }