private static RasterImage CreateTextFooter(LeadSize size, string tag) { var bpp = 24; var byteOrder = RasterByteOrder.Bgr; var viewPerspective = RasterViewPerspective.TopLeft; var image = new RasterImage(RasterMemoryFlags.Conventional, size.Width, size.Height, bpp, byteOrder, viewPerspective, null, null, 0); var fill = new FillCommand(RasterColor.FromKnownColor(RasterKnownColor.White)); fill.Run(image); using (var graphics = RasterImagePainter.CreateGraphics(image)) { using (var brush = new SolidBrush(Color.Black)) { using (var font = new Font(FontFamily.GenericSansSerif, size.Width / 128)) { var pos = new PointF(0, 0); { SizeF stringSize = new SizeF(); stringSize = graphics.Graphics.MeasureString(tag, font); float scaleX = (float)size.Width / stringSize.Width; float scaleY = (float)size.Height / stringSize.Height; scaleX = Math.Min(1f, scaleX); scaleY = Math.Min(1f, scaleY); graphics.Graphics.ScaleTransform(scaleX, scaleY); if (size.Height > (int)stringSize.Height) { size.Height = (int)stringSize.Height; } } graphics.Graphics.DrawString(tag, font, Brushes.Black, new PointF(0, 0)); } } } if (size.Height < image.Height) { var crop = new CropCommand(LeadRect.FromLTRB(0, 0, size.Width, size.Height)); crop.Run(image); } return(image); }
private static LEADDocument AddDocumentToCache(LEADDocument largestDocument, IOcrEngine ocrEngine, Uri documentUri, LoadDocumentOptions loadOptions, DocumentCacheOptions cacheOptions) { // Adds the document to the cache. Note that a new cache entry is created for each different maximumImagePixelSize. var document = DocumentFactory.LoadFromUri(documentUri, loadOptions); try { if (document == null) { throw new InvalidOperationException("Failed to load URI: " + documentUri); } // We will modify this document... bool wasReadOnly = document.IsReadOnly; document.IsReadOnly = false; if (document.Text.TextExtractionMode != DocumentTextExtractionMode.OcrOnly && !document.Images.IsSvgSupported && ocrEngine != null) { document.Text.OcrEngine = ocrEngine; } // Set in the cache options that we want document.CacheOptions = cacheOptions; // prepare the document, caching as much as possible. if (document.IsStructureSupported && !document.Structure.IsParsed) { document.Structure.Parse(); } // Need to cache the SVG with and without getting the back image var loadSvgOptions = new CodecsLoadSvgOptions(); foreach (var page in document.Pages) { // If we have a previous largest document, use the same // SVG and text instead of recreating them (they do not change based on image size) DocumentPage largestDocumentPage = null; if (largestDocument != null) { largestDocumentPage = largestDocument.Pages[page.PageNumber - 1]; } if (cacheOptions == DocumentCacheOptions.None) { // We are done, do not cache the images, svg or text continue; } if ((cacheOptions & DocumentCacheOptions.PageSvg) == DocumentCacheOptions.PageSvg) { // SVG, this does not depend on the image size using (var svg = page.GetSvg(null)) { } using (var svg = page.GetSvg(loadSvgOptions)) { } } if ((cacheOptions & DocumentCacheOptions.PageSvgBackImage) == DocumentCacheOptions.PageSvgBackImage) { // SVG back image, this is different based on the image size using (var svgBack = page.GetSvgBackImage(RasterColor.FromKnownColor(RasterKnownColor.White))) { } } if ((cacheOptions & DocumentCacheOptions.PageImage) == DocumentCacheOptions.PageImage) { // Image, this is different based on the image size using (var image = page.GetImage()) { } } if ((cacheOptions & DocumentCacheOptions.PageThumbnailImage) == DocumentCacheOptions.PageThumbnailImage) { // Thumbnail, this does not depend on the image size but there is no set thumbnail method using (var thumbnailImage = page.GetThumbnailImage()) { } } if ((cacheOptions & DocumentCacheOptions.PageText) == DocumentCacheOptions.PageText) { // Text, this does not depend on the image size if (largestDocumentPage == null) { page.GetText(); } else { var pageText = largestDocumentPage.GetText(); page.SetText(pageText); } } } document.AutoDeleteFromCache = false; document.AutoDisposeDocuments = true; document.AutoSaveToCache = false; // Stop caching document.CacheOptions = DocumentCacheOptions.None; document.IsReadOnly = wasReadOnly; // save it to the regular cache document.SaveToCache(); return(document); } catch (Exception) { if (document != null) { document.Dispose(); } throw; } }
private void ShowMousePositionAndImageColor(RasterImage image, LeadPoint viewerPoint, LeadPoint imagePoint) { // This point is now in image coordinates, i.e., 0,0 is the top-left area of the image // Since we passed 'false' to 'accountForViewPerspective' above, the point is what we see // if the data in the image is top-left (point 0, 0, is the most left-top point in the image data) // This is called the ViewPerspective of the image. Not all images supported by LEADTOOLS have top-left coordinates, // for example, when you load a BMP file, by the default, the image data is "flipped" and has a view perspective of // bottom-left. We could pass 'true' for images like that if we need to convert the point to the // actual pixel x, y in the image. We will do that later in the code below string imagePointText; bool outside = false; // Check if the viewer point is outside the image coordinates if (imagePoint.X < 0 || imagePoint.Y < 0 || imagePoint.X > image.ImageWidth || imagePoint.Y > image.ImageHeight) { outside = true; } if (outside) { // Outside imagePointText = "OUTSIDE"; } else { imagePointText = string.Format("{0}, {1}", imagePoint.X, imagePoint.Y); } // Show both points _mousePositionLabel.Text = string.Format( "Viewer: {0}, {1} - Image: {2}", viewerPoint.X, viewerPoint.Y, imagePointText); // Get the color under the cursor RasterColor pointCursorColor; // Use the imagePoint, we will use Raster.GetPixel. This method except the points // to be in image coordinates and in the image view perspective. // Since we had the point in top-left (by not passing true to accountForViewPerspective), // we must convert it to image coordinate first using RasterImage.PointToImage if (!outside) { LeadPoint colorPoint = new LeadPoint(imagePoint.X, imagePoint.Y); colorPoint = image.PointToImage(RasterViewPerspective.TopLeft, colorPoint); // GetPixel takes row/column, or Y and X pointCursorColor = image.GetPixel(colorPoint.Y, colorPoint.X); } else { // Either outside the image or we do not have an image pointCursorColor = RasterColor.FromKnownColor(RasterKnownColor.Transparent); } _cursorColorValueLabel.Text = pointCursorColor.ToString(); _colorCursorPanel.BackColor = RasterColorConverter.ToColor(pointCursorColor); // Finally, if we are not drawing an interactive user rectangle and the cursor is over the // overlay rect, change its shape to a Hand if (!rubberBandMode.IsEnabled) { if (!_overlayRect.IsEmpty && _overlayRect.Contains(imagePoint.X, imagePoint.Y)) { _imageViewer.Cursor = Cursors.Hand; } else { _imageViewer.Cursor = Cursors.Default; } } }
//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); }
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(); } } } } }
private void CleanupImage(RasterImage imageToClean, int startIndex, int count) { try { //Deskew if (cleanUpOcrEngine != null && cleanUpOcrEngine.IsStarted) { using (IOcrDocument document = cleanUpOcrEngine.DocumentManager.CreateDocument()) { for (var i = startIndex; i < startIndex + count; i++) { imageToClean.Page = i; document.Pages.AddPage(imageToClean, null); int angle = -document.Pages[0].GetDeskewAngle(); RotateCommand cmd = new RotateCommand(angle * 10, RotateCommandFlags.Bicubic, RasterColor.FromKnownColor(RasterKnownColor.White)); cmd.Run(imageToClean); document.Pages.Clear(); } } } else { for (var i = startIndex; i < startIndex + count; i++) { imageToClean.Page = i; var deskewCommand = new DeskewCommand(); if (imageToClean.Height > 3500) { deskewCommand.Flags = DeskewCommandFlags.DocumentAndPictures | DeskewCommandFlags.DoNotPerformPreProcessing | DeskewCommandFlags.UseNormalDetection | DeskewCommandFlags.DoNotFillExposedArea; } else { deskewCommand.Flags = DeskewCommandFlags.DeskewImage | DeskewCommandFlags.DoNotFillExposedArea; } deskewCommand.Run(imageToClean); } } } catch (Exception ex) { //log.Error(ex); Console.WriteLine("Not recognized"); } }
private void DrawImage(PaintEventArgs e, Rectangle clipRect) { if (_documents.Count == 0) { return; } if (_documents[_currentPageIndex].Document == null || !this.CanUpdate) { return; } var graphics = e.Graphics; var options = new SvgRenderOptions(); options.Transform = _transform; options.Bounds = _documents[_currentPageIndex].Document.Bounds.Bounds; options.UseBackgroundColor = true; options.ClipBounds = LeadRectD.Create(clipRect.X, clipRect.Y, clipRect.Width, clipRect.Height); options.BackgroundColor = RasterColor.FromKnownColor(RasterKnownColor.White); try { using (var engine = RenderingEngineFactory.Create(graphics)) _documents[_currentPageIndex].Document.Render(engine, options); } catch { Console.WriteLine(); } DrawBounds(graphics, Pens.Black, null, null, null, null, options.Bounds, options.Transform); if (_documents[_currentPageIndex].DocumentText != null && _documents[_currentPageIndex].ShowText) { LeadRectD docBounds = _documents[_currentPageIndex].Document.Bounds.Bounds; // Could be rotated, so LeadPointD topLeft = docBounds.TopLeft; LeadPointD bottomRight = docBounds.BottomRight; LeadPointD[] corners = new LeadPointD[4]; corners[0].X = topLeft.X; corners[0].Y = topLeft.Y; corners[1].X = bottomRight.X; corners[1].Y = topLeft.Y; corners[2].X = bottomRight.X; corners[2].Y = bottomRight.Y; corners[3].X = topLeft.X; corners[3].Y = bottomRight.Y; options.Transform.TransformPoints(corners); GraphicsPath path = new GraphicsPath(); PointF[] pts = new PointF[4]; for (int i = 0; i < corners.Length; i++) { pts[i].X = (float)corners[i].X; pts[i].Y = (float)corners[i].Y; } path.AddPolygon(pts); graphics.SetClip(path, System.Drawing.Drawing2D.CombineMode.Intersect); using (var brush = new SolidBrush(Color.FromArgb(64, Color.Black))) { foreach (var character in _documents[_currentPageIndex].DocumentText.Characters) { var bounds = character.Bounds; var text = new string(new char[] { character.Code }); DrawBounds(graphics, Pens.Yellow, brush, Brushes.Yellow, Font, text, character.Bounds, options.Transform); } } } base.OnPaint(e); }
private bool CleanupImage(RasterImage imageToClean, int startIndex, int count) { try { if (this.IsStartedOcrEngine()) { using (IOcrDocument document = this.TheOcrEngine.DocumentManager.CreateDocument()) { for (var i = startIndex; i < startIndex + count; i++) { imageToClean.Page = i; document.Pages.AddPage(imageToClean, null); int angle = -document.Pages[0].GetDeskewAngle(); RotateCommand cmd = new RotateCommand(angle * 10, RotateCommandFlags.Bicubic, RasterColor.FromKnownColor(RasterKnownColor.White)); cmd.Run(imageToClean); document.Pages.Clear(); } } } else { for (var i = startIndex; i < startIndex + count; i++) { imageToClean.Page = i; var deskewCommand = new DeskewCommand(); if (imageToClean.Height > 3500) { deskewCommand.Flags = DeskewCommandFlags.DocumentAndPictures | DeskewCommandFlags.DoNotPerformPreProcessing | DeskewCommandFlags.UseNormalDetection | DeskewCommandFlags.DoNotFillExposedArea; } else { deskewCommand.Flags = DeskewCommandFlags.DeskewImage | DeskewCommandFlags.DoNotFillExposedArea; } deskewCommand.Run(imageToClean); } } return(true); } catch (Exception ex) { return(false); } }