public void CompressImage(string SourceFileName, string DestFileName) { RasterCodecs codecs = new RasterCodecs(); RasterImage sourceImage = codecs.Load(SourceFileName); RasterImage destinationImage = new RasterImage( RasterMemoryFlags.Conventional, sourceImage.Width, sourceImage.Height, sourceImage.BitsPerPixel, sourceImage.Order, sourceImage.ViewPerspective, sourceImage.GetPalette(), IntPtr.Zero, 0); sourceImage.Access(); destinationImage.Access(); byte[] buffer = new byte[sourceImage.BytesPerLine]; for (int y = 0; y < sourceImage.Height; y++) { sourceImage.GetRow(y, buffer, 0, buffer.Length); destinationImage.SetRow(y, buffer, 0, buffer.Length); } destinationImage.Release(); sourceImage.Release(); // We do not need the source image anymore sourceImage.Dispose(); // save the destination image codecs.Save(destinationImage, DestFileName, RasterImageFormat.Tif, 24); // perform image processing on the image //FlipCommand flipCmd = new FlipCommand(); //flipCmd.Horizontal = false; //flipCmd.Run(destinationImage); //// save it //codecs.Save(destinationImage, destFileName2, RasterImageFormat.Bmp, 24); // Clean up destinationImage.Dispose(); codecs.Dispose(); codecs.Dispose(); }
protected override void OnFormClosed(FormClosedEventArgs e) { // Clean up // Save the last setting Properties.Settings settings = new Properties.Settings(); if (_ocrEngine != null) { settings.OcrEngineType = _ocrEngine.EngineType.ToString(); } settings.Save(); if (_ocrDocument != null) { _ocrDocument.Dispose(); _ocrDocument = null; } // Dispose the OCR engine (this will call Shutdown as well) if (_ocrEngine != null) { _ocrEngine.Dispose(); _ocrEngine = null; } if (_rasterCodecs != null) { _rasterCodecs.Dispose(); _rasterCodecs = null; } base.OnFormClosed(e); }
public void ConvertTifToPdf(string SourceFileName, string DestFileName) { RasterCodecs CodecsCommand = new RasterCodecs(); RasterImage LeadImage = null; try { UnlockLeadToolsPDFSupport(); //RasterCodecs.CodecsPath = codecsPath; //CodecsCommand.Options.Pdf.InitialPath = pdfInitialPath; CodecsCommand.Options.Pdf.Save.UseImageResolution = true; CodecsCommand.Options.Tiff.Load.IgnoreViewPerspective = true; LeadImage = CodecsCommand.Load(SourceFileName); //LeadImage.ChangeCompression((LeadImage.IsSuperCompressed == true) ? RasterCompression.None : RasterCompression.Super); if (String.IsNullOrEmpty(DestFileName)) { DestFileName = System.IO.Path.Combine(System.IO.Path.GetTempPath().ToString(), Guid.NewGuid().ToString() + ".PDF"); } CodecsCommand.Save(LeadImage, DestFileName, Leadtools.RasterImageFormat.RasPdf, 1, 1, LeadImage.PageCount, 1, Leadtools.Codecs.CodecsSavePageMode.Overwrite); } finally { if (LeadImage != null) { LeadImage.Dispose(); } if (CodecsCommand != null) { CodecsCommand.Dispose(); } } }
public static void Shutdown() { if (codec != null) { codec.Dispose(); } }
private void Dispose(bool disposed) { if (autoEngine != null) { autoEngine.Dispose(); autoEngine = null; } if (ocrEngines != null) { foreach (var ocrEngine in ocrEngines) { ocrEngine.Shutdown(); ocrEngine.Dispose(); } } if (rasterCodecs != null) { rasterCodecs.Dispose(); rasterCodecs = null; } if (cleanUpOcrEngine != null) { cleanUpOcrEngine.Shutdown(); cleanUpOcrEngine.Dispose(); cleanUpOcrEngine = null; } ocrEngines = null; }
//fully qualified path & filename public LT_DPI_Converter(string srcFileName, string destFileName) { RasterCodecs codecs = new RasterCodecs(); System.IO.File.Copy(srcFileName, destFileName, true); //Read Original Values RasterImage oldimage = codecs.Load(srcFileName); //Change values and save a new file name RasterImage newimage = codecs.Load(destFileName); int newResolution = 300; //BR says all files need to be 300 DPI. This should probably be an enum. // Load the source image from disk newimage.XResolution = newResolution; newimage.YResolution = newResolution; SizeCommand command = new SizeCommand(); command.Width = oldimage.Width; command.Height = oldimage.Height; command.Flags = RasterSizeFlags.Resample; command.Run(newimage); //This changes the entire image and all pages. There is no need to pageinate. // Save the image back to disk codecs.Save(newimage, destFileName, RasterImageFormat.Tif, oldimage.BitsPerPixel); // Clean Up newimage.Dispose(); oldimage.Dispose(); codecs.Dispose(); }
private void CleanUp() { // Delete all resources if (_sampleSymbologiesRasterImage != null) { _sampleSymbologiesRasterImage.Dispose(); } if (_rasterCodecs != null) { _rasterCodecs.Dispose(); } }
protected override void OnFormClosed(FormClosedEventArgs e) { if (!DesignMode) { if (_imageInfo != null) { _imageInfo.Dispose(); } _rasterCodecsInstance.Dispose(); } base.OnFormClosed(e); }
private void UpdateMasterFormsData_FormClosing(object sender, FormClosingEventArgs e) { if (!String.IsNullOrEmpty(_txtSrcFolder.Text)) { Properties.Settings.Default.SourceFolder = _txtSrcFolder.Text; } Properties.Settings.Default.Save(); if (UpdateMasterFormsThread != null && UpdateMasterFormsThread.ThreadState == ThreadState.Running) { UpdateMasterFormsThread.Abort(); } _codecs.Dispose(); }
/// <param name="yfile">源图像</param> /// <param name="mfile">新图像</param> /// <param name="p1">页码1</param> /// <param name="p2">页码2</param> /// <param name="fileformat">图像格式</param> public static bool _SplitImg(string yfile, string mfile, int p1, int p2, string fileformat) { try { RasterImageFormat format = new RasterImageFormat(); if (fileformat.IndexOf("jpg") >= 0) { format = RasterImageFormat.Jpeg; } else if (fileformat.IndexOf("pdf") >= 0) { format = RasterImageFormat.RasPdfJpeg; } else if (fileformat.IndexOf("tif") >= 0) { format = RasterImageFormat.TifJpeg; } RasterImage _imagepx; RasterCodecs _Codef = new RasterCodecs(); for (int i = p1; i <= p2; i++) { _imagepx = _Codef.Load(yfile, 0, CodecsLoadByteOrder.BgrOrGrayOrRomm, i, i); int bit = _imagepx.BitsPerPixel; if (bit != 1) { if (bit != 8) { // _Codef.Options.Jpeg.Save.QualityFactor = 80; _Codef.Save(_imagepx, mfile, format, bit, 1, 1, i, CodecsSavePageMode.Append); } else { // _Codef.Options.Jpeg.Save.QualityFactor = Factor; _Codef.Save(_imagepx, mfile, format, 8, 1, 1, i, CodecsSavePageMode.Append); } } else { _Codef.Save(_imagepx, mfile, format, 1, 1, 1, -1, CodecsSavePageMode.Append); } } _Codef.Dispose(); return(true); } catch { return(false); } }
private void _mnuOverlaysSaveOverlay_Click(object sender, EventArgs e) { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Windows Bitmap (*.bmp)|*.bmp"; dlg.FilterIndex = 0; if (dlg.ShowDialog() == DialogResult.OK) { int selected = _rasterImageList.Items.IndexOf(_rasterImageList.Items.GetSelected()[0]); RasterImage overlay = _rasterImageViewer.Image.GetOverlayImage(selected, RasterGetSetOverlayImageMode.Copy); RasterCodecs codecs = new RasterCodecs(); codecs.Save(overlay, dlg.FileName, RasterImageFormat.Bmp, overlay.BitsPerPixel); codecs.Dispose(); overlay.Dispose(); } }
void CleanUp() { if (_ocrPage != null) { _ocrPage.Dispose(); _ocrPage = null; } if (_ocrEngine != null && _ocrEngine.IsStarted) { _ocrEngine.Shutdown(); _ocrEngine.Dispose(); } if (_codecs != null) { _codecs.Dispose(); } }
public void ConvertToGrayScale(string SourceFileName, string DestFileName) { RasterImage image = null; RasterCodecs codecs = new RasterCodecs(); int pageCount = 0; image = codecs.Load(SourceFileName); pageCount = image.PageCount; //RasterImage resizedImage = ResizeImage(image, codecs); var bitsPerPixel = 12; //if (convertToGrayScale) // bitsPerPixel = 12; codecs.Save(image, DestFileName, RasterImageFormat.Tif, bitsPerPixel, 1, pageCount, 1, CodecsSavePageMode.Insert); image.Dispose(); codecs.Dispose(); }
public static void exe_ocr(string filename, IOcrDocument ocrDocument) { Console.WriteLine(filename); RasterCodecs rasterCodecs = null; RasterImage rasterImage = null; try { rasterCodecs = new RasterCodecs(); rasterCodecs.ThrowExceptionsOnInvalidImages = false; rasterImage = rasterCodecs.Load(filename); AutoBinarizeCommand command = new AutoBinarizeCommand(); command.Run(rasterImage); //AutoLineRemoveCommand commandLine = new AutoLineRemoveCommand(); //commandLine.Run(rasterImage); IOcrPage page = ocrDocument.Pages.AddPage(rasterImage, null); if (page != null) { page.UpdateNativeFillMethod(); page.Recognize(null); } // ocrDocument.Pages.zon(NativeOcrZoneType.AutoGraphic); }catch (Exception e) { // Console.WriteLine("add image faild: " + e); } finally { if (rasterCodecs != null) { rasterCodecs.Dispose(); } if (rasterImage != null) { rasterImage.Dispose(); } } }
protected override void OnFormClosing(FormClosingEventArgs e) { if (_codecs != null) { _codecs.Dispose(); } if (_viewer.Items.Count > 0 && _viewer.Items[0].HasFloater && _viewer.Items[0].Floater != null && !_viewer.Items[0].Floater.IsDisposed) { _viewer.Items[0].Floater.Dispose(); _viewer.Items[0].Floater = null; } if (_viewer.Image != null && !_viewer.Image.IsDisposed) { _viewer.Image.Dispose(); } base.OnFormClosing(e); }
public void ConvertPdfToTif(string SourceFileName, string DestFileName) { using (RasterCodecs codecs = new RasterCodecs()) { codecs.Options.Pdf.InitialPath = _pdfInitialPath;; PDFDocument document = new PDFDocument(SourceFileName); for (int pageNumber = 1; pageNumber <= document.Pages.Count; pageNumber++) { // Render the page into a raster image using (RasterImage image = document.GetPageImage(codecs, pageNumber)) { // Append to (or create if it does not exist) a TIFF file codecs.Save(image, DestFileName, RasterImageFormat.Tif, 24, 1, 1, -1, CodecsSavePageMode.Append); image.Dispose(); } } codecs.Dispose(); } }
public void ConvertDpi(string srcFileName, string destFileName) { RasterCodecs codecs = new RasterCodecs(); RasterImage image = codecs.Load(srcFileName); int newResolution = 300; //BR says all files need to be 300 DPI. This should probably be an enum. image.XResolution = newResolution; image.YResolution = newResolution; SizeCommand command = new SizeCommand(); command.Width = image.Width; command.Height = image.Height; command.Flags = RasterSizeFlags.Resample; command.Run(image); codecs.Save(image, destFileName, RasterImageFormat.Tif, image.BitsPerPixel); image.Dispose(); codecs.Dispose(); }
protected override void OnFormClosed(FormClosedEventArgs e) { // Save last settings used Properties.Settings settings = new Properties.Settings(); settings.Url = _serverProperties.Url; settings.UseCredentials = _serverProperties.UseCredentials.ToString(); settings.UserName = _serverProperties.UserName; settings.Domain = _serverProperties.Domain; settings.UseProxy = _serverProperties.UseProxy.ToString(); settings.Host = _serverProperties.Host; settings.Port = _serverProperties.Port.ToString(); settings.Save(); // Dispose the RasterCodecs object we used if (_codecs != null) { _codecs.Dispose(); } base.OnFormClosed(e); }
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e) { try { DeleteTempFiles(); //Application will exit, delete font files DeleteAndUninstallFonts(); if (Directory.Exists(_fontsPath)) { Directory.Delete(_fontsPath, true); } if (_codec != null) { _codec.Dispose(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private void InternalPrint(PrintJob job) { BasicFilmSessionModuleIod basicFilmSessionModuleIod = new BasicFilmSessionModuleIod { NumberOfCopies = job.Copies, MediumType = job.MediumType, FilmDestination = job.FilmDestination }; BasicFilmBoxModuleIod basicFilmBoxModuleIod = new BasicFilmBoxModuleIod { //ImageDisplayFormat = @"STANDARD\1,1", ImageDisplayFormat = ImageDisplayFormat.Standard_1x1, FilmSizeId = job.FilmSize, Illumination = job.Illumination, FilmOrientation = job.FilmOrientation, ReflectedAmbientLight = job.ReflectedAmbientLight, MagnificationType = job.MagnificationType }; IList <ImageBoxPixelModuleIod> imageBoxPixelModuleIods = new List <ImageBoxPixelModuleIod>(); bool userCancelled = false; BackgroundTask task = new BackgroundTask(delegate(IBackgroundTaskContext context) { try { BackgroundTaskProgress progress; ushort num = 1; int percent = 0; new List <string>(); ImageBoxPixelModuleIod item = new ImageBoxPixelModuleIod { ImageBoxPosition = 1 }; BasicGrayscaleImageSequenceIod iod2 = new BasicGrayscaleImageSequenceIod { PhotometricInterpretation = job.MonochormeType }; Size size = this.CalcMaxSize(job.Format, job.Images); Bitmap image = new Bitmap(size.Width, size.Height); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image); foreach (PreviewTile tile in job.Images) { percent = (int)((((float)(num - 1)) / ((float)job.Images.Count)) * 80f); num = (ushort)(num + 1); progress = new BackgroundTaskProgress(percent, string.Format(SR.CreatingImageBuffer, num, job.Images.Count)); context.ReportProgress(progress); if (tile.ImageData != null) { Platform.Log(LogLevel.Error, "TITLE IMAGEDATA"); Bitmap printImagePixel = tile.GetPrintImagePixel(false); float x = tile.NormalizedRectangle.X * size.Width; float y = tile.NormalizedRectangle.Y * size.Height; float width = tile.NormalizedRectangle.Width * size.Width; float height = tile.NormalizedRectangle.Height * size.Height; g.DrawImage(printImagePixel, x, y, width, height); g.DrawRectangle(Pens.White, x, y, width, height); Rectangle destination = new Rectangle(((int)x) + 2, ((int)y) + 2, ((int)width) - 4, ((int)height) - 4); try { IconCreator.DrawTextOverlay(g, destination, tile.ImageData); } catch (Exception ex) { Platform.Log(LogLevel.Error, " exception: " + ex.ToString()); } printImagePixel.Dispose(); if (context.CancelRequested) { userCancelled = true; break; } } } //clear foreach (PreviewTile tile in job.Images) { ImageSop sop = ((IImageSopProvider)tile.ImageData).ImageSop; string strUID = sop.SopInstanceUid; //获取UID 的 accession try { if (Conn.isOracle()) { string sqlstr = string.Format(" update examrecord set filmprint='{0}' where id=(select AccessionNumber from images where SopInstanceUID='{1}') and modulename='RIS' ", "1", strUID); OracleCommand sqlCmd = new OracleCommand(); sqlCmd.Connection = GlobalData.MainConn.ChangeTypeOracle(); sqlCmd.CommandText = sqlstr; sqlCmd.ExecuteNonQuery(); sqlCmd.Dispose(); } else { string sqlstr = string.Format(" update examrecord set filmprint='{0}' where id=(select AccessionNumber from images where SopInstanceUID='{1}') and modulename='RIS' ", "1", strUID); SqlCommand sqlCmd = new SqlCommand(); sqlCmd.Connection = GlobalData.MainConn.ChangeType(); sqlCmd.CommandText = sqlstr; sqlCmd.ExecuteNonQuery(); sqlCmd.Dispose(); Platform.Log(LogLevel.Error, " sql is " + sqlstr); } } catch (Exception ex) { Platform.Log(LogLevel.Error, "exception is " + ex.ToString()); } //tile.Dispose(); tile.RemoveImage(); } job.Images.Clear(); g.Dispose(); //iod2.AddBitmap(image); Unlock(); RasterImage lRasterImage = null; RasterCodecs lRasterCodecs = new RasterCodecs(); lRasterImage = RasterImageConverter.ConvertFromImage(image, ConvertFromImageOptions.None); lRasterCodecs.Save(lRasterImage, System.Windows.Forms.Application.StartupPath + @"\print.jpg", RasterImageFormat.Tif, 8); string lDicomFile = "1" + DateTime.Now.ToString("HHmmss", DateTimeFormatInfo.InvariantInfo); lRasterCodecs.Save(lRasterImage, System.Windows.Forms.Application.StartupPath + @"\PrintFiles\" + lDicomFile, RasterImageFormat.DicomGray, 16); //image.Save("d:\\test.jpg"); image.Dispose(); lRasterImage.Dispose(); lRasterCodecs.Dispose(); //item.BasicGrayscaleImageSequenceList.Add(iod2); //imageBoxPixelModuleIods.Add(item); if (userCancelled) { Platform.Log(LogLevel.Info, SR.UserCancel); } else { progress = new BackgroundTaskProgress(80, SR.BeginSendImage); context.ReportProgress(progress); PrintDicomFiles(lDicomFile, 1, 1, lDicomFile, job); //BasicGrayscalePrintScu scu = new BasicGrayscalePrintScu(); //scu.Print(job.Printer.AET, job.Printer.CalledAET, job.Printer.Host, job.Printer.Port, basicFilmSessionModuleIod, basicFilmBoxModuleIod, imageBoxPixelModuleIods); //if (scu.ResultStatus == DicomState.Success) //{ // this.UpdateStudyPrintStatus(this.GetStudyInstanceUIDs(job.Images)); // PrintToolComponent.TilesComponent.ResetTiles(); //} //else //{ // this._component.ShowMessageBox(SR.FilmError); //} } } catch (OutOfMemoryException) { Platform.Log(LogLevel.Error, "内存不够"); BackgroundTaskProgress progress2 = new BackgroundTaskProgress(100, SR.OutOfMemory); context.ReportProgress(progress2); this._component.ShowMessageBox(SR.OutOfMemory); } catch (Exception exception) { Platform.Log(LogLevel.Error, exception.Message); BackgroundTaskProgress progress3 = new BackgroundTaskProgress(100, exception.Message); context.ReportProgress(progress3); this._component.ShowMessageBox(SR.PrinterError); } finally { context.Complete(null); } }, true); ProgressDialog.Show(task, this._window, true, ProgressBarStyle.Blocks); }
///---------------------------------------------------------------- /// <summary> /// 伝票画像表示 </summary> /// <param name="iX"> /// 現在の伝票</param> /// <param name="tempImgName"> /// 画像名</param> ///---------------------------------------------------------------- public void ShowImage(string tempImgName) { //string wrkFileName; //修正画面へ組み入れた画像フォームの表示 //画像の出力が無い場合は、画像表示をしない。 if (tempImgName == string.Empty) { leadImg.Visible = false; //global.pblImageFile = string.Empty; return; } //画像ファイルがあるときのみ表示 //wrkFileName = tempImgName; if (System.IO.File.Exists(tempImgName)) { leadImg.Visible = true; //画像ロード RasterCodecs.Startup(); RasterCodecs cs = new RasterCodecs(); // 描画時に使用される速度、品質、およびスタイルを制御します。 RasterPaintProperties prop = new RasterPaintProperties(); prop = RasterPaintProperties.Default; prop.PaintDisplayMode = RasterPaintDisplayModeFlags.Resample; leadImg.PaintProperties = prop; leadImg.Image = cs.Load(tempImgName, 0, CodecsLoadByteOrder.BgrOrGray, 1, 1); //画像表示倍率設定 if (gl.miMdlZoomRate == 0f) { if (leadImg.ImageDpiX == 200) { leadImg.ScaleFactor *= gl.ZOOM_RATE; // 200*200 画像のとき } else { leadImg.ScaleFactor *= gl.ZOOM_RATE; // 300*300 画像のとき } } else { leadImg.ScaleFactor *= gl.miMdlZoomRate; } //画像のマウスによる移動を可能とする leadImg.InteractiveMode = RasterViewerInteractiveMode.Pan; ////右へ90°回転させる //RotateCommand rc = new RotateCommand(); //rc.Angle = 90 * 100; //rc.FillColor = new RasterColor(255, 255, 255); ////rc.Flags = RotateCommandFlags.Bicubic; //rc.Flags = RotateCommandFlags.Resize; //rc.Run(leadImg.Image); // グレースケールに変換 GrayscaleCommand grayScaleCommand = new GrayscaleCommand(); grayScaleCommand.BitsPerPixel = 8; grayScaleCommand.Run(leadImg.Image); leadImg.Refresh(); cs.Dispose(); RasterCodecs.Shutdown(); //global.pblImageFile = wrkFileName; // 画像操作ボタン btnPlus.Enabled = true; btnMinus.Enabled = true; } else { //画像ファイルがないとき leadImg.Visible = false; //global.pblImageFile = string.Empty; // 画像操作ボタン btnPlus.Enabled = false; btnMinus.Enabled = false; } }
static int Main(string[] args) { Messager.Caption = "C# OCR Auto Recognize Demo"; #if LEADTOOLS_V175_OR_LATER if (!Support.SetLicense()) { return(-1); } #else Leadtools.Demos.Support.Unlock(false); #endif // #if LEADTOOLS_V175_OR_LATER _handler += new EventHandler(Handler); SetConsoleCtrlHandler(_handler, true); // Trace to the console Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); JobData jobData = new JobData(); RasterCodecs _rasterCodecs = new RasterCodecs(); #if !LEADTOOLS_V175_OR_LATER _rasterCodecs.Options.RasterizeDocument.Load.Enabled = true; #endif _rasterCodecs.Options.Pdf.Load.DisplayDepth = 24; #if LEADTOOLS_V16_OR_LATER // Use the new RasterizeDocumentOptions to default loading document files at 300 DPI _rasterCodecs.Options.RasterizeDocument.Load.XResolution = 300; _rasterCodecs.Options.RasterizeDocument.Load.YResolution = 300; _rasterCodecs.Options.Pdf.Load.EnableInterpolate = true; _rasterCodecs.Options.Load.AutoFixImageResolution = true; #endif // #if LEADTOOLS_V16_OR_LATER bool unexpectedShutdown = false; try { do { // Get the demo job data JobForm form = new JobForm(_rasterCodecs); form.JobData = jobData; if (form.ShowDialog() != DialogResult.OK) { Console.WriteLine("Exiting"); return(0); } bool deleteExistingFile = File.Exists(form.JobData.DocumentFileName); if (deleteExistingFile && form.JobData.Format == DocumentFormat.Ltd) { // This is an LTD file that already exists, so ask the user what to do here, delete or append to it var message = string.Format("Delete the existing output file '{0}' first?{1}The file already exists. Select 'Yes' to delete it and create a new one or 'No' to append this result to it.", form.JobData.DocumentFileName, Environment.NewLine); switch (Messager.ShowQuestion(null, message, MessageBoxButtons.YesNoCancel)) { case DialogResult.Yes: deleteExistingFile = true; break; case DialogResult.No: deleteExistingFile = false; break; default: continue; } } // Delete the output file first if (deleteExistingFile) { File.Delete(form.JobData.DocumentFileName); } // Now run IOcrAutoRecognizeManager ocrAutoRecognizeManager = jobData.OcrEngine.AutoRecognizeManager; ocrAutoRecognizeManager.EnableTrace = jobData.EnableTrace; ocrAutoRecognizeManager.MaximumThreadsPerJob = jobData.MaximumThreadsPerJob; ocrAutoRecognizeManager.MaximumPagesBeforeLtd = jobData.MaximumPagesBeforeLtd; ocrAutoRecognizeManager.JobErrorMode = jobData.JobErrorMode; ocrAutoRecognizeManager.PreprocessPageCommands.Clear(); foreach (OcrAutoPreprocessPageCommand command in jobData.PreprocessPageCommands) { ocrAutoRecognizeManager.PreprocessPageCommands.Add(command); } Console.WriteLine("Running job..."); Stopwatch watch = new Stopwatch(); watch.Start(); // get an OCR job OcrAutoRecognizeJobData ocrJobData = new OcrAutoRecognizeJobData( jobData.ImageFileName, jobData.FirstPageNumber, jobData.LastPageNumber, jobData.ZonesFileName, jobData.Format, jobData.DocumentFileName); ocrJobData.JobName = "MyJob"; IOcrAutoRecognizeJob ocrJob = ocrAutoRecognizeManager.CreateJob(ocrJobData); try { ocrAutoRecognizeManager.RunJob(ocrJob); } catch (Exception) { } watch.Stop(); Console.WriteLine("----------------------------"); if (ocrJob.Errors.Count > 0) { Console.WriteLine("Errors found:"); foreach (OcrAutoRecognizeManagerJobError error in ocrJob.Errors) { Console.WriteLine("Page: {0} - Operation: {1} - Error: {2}", error.ImagePageNumber, error.Operation, error.Exception); } } Console.WriteLine("Total conversion time: " + watch.Elapsed.ToString()); Console.WriteLine("----------------------------"); if (jobData.ViewFinalDocument && jobData.Format != DocumentFormat.Ltd) { try { System.Diagnostics.Process.Start(jobData.DocumentFileName); } catch (Exception ex) { Messager.ShowError(null, ex); } } }while(true); } catch (OcrException ex) { unexpectedShutdown = true; Console.WriteLine("OCR error code: {0}\n{1}", ex.Code, ex.Message); return(1); } catch (RasterException ex) { unexpectedShutdown = true; Console.WriteLine("LEADTOOLS error code: {0}\n{1}", ex.Code, ex.Message); return(1); } catch (Exception ex) { unexpectedShutdown = true; Console.WriteLine("Error: " + ex.Message); return(1); } finally { _handler -= new EventHandler(Handler); if (jobData.OcrEngine != null) { // Dispose the OCR engine (this will call Shutdown as well) jobData.OcrEngine.Dispose(); jobData.OcrEngine = null; } if (_rasterCodecs != null) { _rasterCodecs.Dispose(); _rasterCodecs = null; } if (unexpectedShutdown) { Console.WriteLine("Hit Enter..."); while (Console.ReadKey(true).Key != ConsoleKey.Enter) { } } } }
/// <summary> /// Load a new image /// </summary> private void _miFileOpen_Click(object sender, System.EventArgs e) { RasterCodecs _codecs = null; CodecsImageInfo imageInfo = null; try { // initialize the codecs object. _codecs = new RasterCodecs(); // Since we are dealing with large images, we do not want to allocate the entire image. We are only going to load it row by row _codecs.Options.Load.AllocateImage = false; _codecs.Options.Load.StoreDataInImage = false; _codecs.LoadImage += new EventHandler <CodecsLoadImageEventArgs>(codecs_LoadImage); // load the image OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Title = "Open File"; openFileDialog.Multiselect = false; if (openFileDialog.ShowDialog() == DialogResult.OK) { //Check if image is valid for this demo imageInfo = _codecs.GetInformation(openFileDialog.FileName, false); if (!IsImageValid(imageInfo)) { Messager.ShowError(this, "The input image has to be 8-bit Gray scale, 12-bit Gray scale, 16-bit Gray scale, RGB (color), and TopLeft view perspective." + " This DEMO is not meant to be used with small or palletized images (like GIF, PNG, or 1-bit images)." + " Use this DEMO to save large dimension images efficiently using JPEG2000 compression."); return; } using (RasterSaveDialog saveDialog = new RasterSaveDialog(_codecs)) { saveDialog.AutoProcess = false; saveDialog.Title = "Save As"; saveDialog.ShowFileOptionsBasicJ2kOptions = true; saveDialog.ShowFileOptionsJ2kOptions = true; saveDialog.ShowOptions = true; saveDialog.ShowQualityFactor = true; saveDialog.ShowFileOptionsProgressive = true; saveDialog.ShowFileOptionsStamp = true; saveDialog.QualityFactor = 20; SetupFormats(saveDialog); if (saveDialog.ShowDialog(this) != DialogResult.OK) { return; } _lblFilenameValue.Text = Path.GetFileName(openFileDialog.FileName); _lblDimensionValue.Text = String.Format("{0} x {1}", imageInfo.Width, imageInfo.Height); _lblImageBitsPerPixelValue.Text = imageInfo.BitsPerPixel.ToString(); //Get the selected compression type CodecsCompression selectedCompression; if (saveDialog.Format == RasterImageFormat.J2k) { selectedCompression = CodecsCompression.J2k; } else { selectedCompression = CodecsCompression.Jp2; } RasterByteOrder rasterByteOrder = ((saveDialog.BitsPerPixel == 12) || (saveDialog.BitsPerPixel == 16)) ? RasterByteOrder.Gray : RasterByteOrder.Bgr; CodecsLoadByteOrder codecsLoadByteOrder = ((saveDialog.BitsPerPixel == 12) || (saveDialog.BitsPerPixel == 16)) ? CodecsLoadByteOrder.Gray : CodecsLoadByteOrder.Bgr; bytesPerLine = CalculateBytesPerLine(saveDialog.BitsPerPixel, imageInfo.Width); _codecs.Options.Jpeg.Save.QualityFactor = saveDialog.QualityFactor; _codecs.Options.Jpeg.Save.Passes = saveDialog.Passes; _codecs.Options.Jpeg.Save.SaveWithStamp = saveDialog.WithStamp; _codecs.Options.Jpeg.Save.StampWidth = saveDialog.StampWidth; _codecs.Options.Jpeg.Save.StampHeight = saveDialog.StampHeight; _codecs.Options.Jpeg.Save.StampBitsPerPixel = saveDialog.StampBitsPerPixel; _codecs.Options.Jpeg2000.Save.CompressionControl = saveDialog.FileJ2kOptions.CompressionControl; _codecs.Options.Jpeg2000.Save.CompressionRatio = saveDialog.FileJ2kOptions.CompressionRatio; _codecs.Options.Jpeg2000.Save.DecompositionLevels = saveDialog.FileJ2kOptions.DecompositionLevels; _codecs.Options.Jpeg2000.Save.DerivedQuantization = saveDialog.FileJ2kOptions.DerivedQuantization; _codecs.Options.Jpeg2000.Save.ImageAreaHorizontalOffset = saveDialog.FileJ2kOptions.ImageAreaHorizontalOffset; _codecs.Options.Jpeg2000.Save.ImageAreaVerticalOffset = saveDialog.FileJ2kOptions.ImageAreaVerticalOffset; _codecs.Options.Jpeg2000.Save.ProgressingOrder = saveDialog.FileJ2kOptions.ProgressingOrder; _codecs.Options.Jpeg2000.Save.ReferenceTileHeight = saveDialog.FileJ2kOptions.ReferenceTileHeight; _codecs.Options.Jpeg2000.Save.ReferenceTileWidth = saveDialog.FileJ2kOptions.ReferenceTileWidth; _codecs.Options.Jpeg2000.Save.RegionOfInterest = saveDialog.FileJ2kOptions.RegionOfInterest; _codecs.Options.Jpeg2000.Save.RegionOfInterestRectangle = saveDialog.FileJ2kOptions.RegionOfInterestRectangle; _codecs.Options.Jpeg2000.Save.RegionOfInterestWeight = saveDialog.FileJ2kOptions.RegionOfInterestWeight; _codecs.Options.Jpeg2000.Save.TargetFileSize = saveDialog.FileJ2kOptions.TargetFileSize; _codecs.Options.Jpeg2000.Save.TileHorizontalOffset = saveDialog.FileJ2kOptions.TileHorizontalOffset; _codecs.Options.Jpeg2000.Save.TileVerticalOffset = saveDialog.FileJ2kOptions.TileVerticalOffset; _codecs.Options.Jpeg2000.Save.UseColorTransform = saveDialog.FileJ2kOptions.UseColorTransform; _codecs.Options.Jpeg2000.Save.UseEphMarker = saveDialog.FileJ2kOptions.UseEphMarker; _codecs.Options.Jpeg2000.Save.UseRegionOfInterest = saveDialog.FileJ2kOptions.UseRegionOfInterest; _codecs.Options.Jpeg2000.Save.UseSopMarker = saveDialog.FileJ2kOptions.UseSopMarker; bCancel = false; bCompressing = true; UpdateMyControls(); //Start Compressing using (outputFile = File.Create(saveDialog.FileName)) { _codecs.StartCompress(imageInfo.Width, imageInfo.Height, saveDialog.BitsPerPixel, rasterByteOrder, RasterViewPerspective.TopLeft, bytesPerLine, IntPtr.Zero, 0, selectedCompression, MyCodecsCompressDataCallback); _codecs.Load(openFileDialog.FileName, saveDialog.BitsPerPixel, codecsLoadByteOrder, 1, 1); _codecs.StopCompress(); _lblStatusValue.Text = bCancel ? "Aborted" : "Complete"; } } } } catch (Exception ex) { Messager.ShowError(this, ex); _lblStatusValue.Text = "Error"; } finally { if (_codecs != null) { _codecs.Dispose(); } if (imageInfo != null) { imageInfo.Dispose(); } bCompressing = false; UpdateMyControls(); } }
public List <string> ProcessFilesMultiThread(string FileOrDir) { //============================ // root path string rootPath = Path.Combine("C:\\", "Lateetud"); if (!Directory.Exists(rootPath)) { Directory.CreateDirectory(rootPath); } if (!Directory.Exists(Path.Combine(rootPath, TheVarSubDir.License))) { Directory.CreateDirectory(Path.Combine(rootPath, TheVarSubDir.License)); } if (!Directory.Exists(Path.Combine(rootPath, TheVarSubDir.OCRInput))) { Directory.CreateDirectory(Path.Combine(rootPath, TheVarSubDir.OCRInput)); } if (!Directory.Exists(Path.Combine(rootPath, TheVarSubDir.OCRMasterFormSets))) { Directory.CreateDirectory(Path.Combine(rootPath, TheVarSubDir.OCRMasterFormSets)); } //============================ //============================ // set the license RasterSupport.SetLicense(Path.Combine(rootPath, TheVarSubDir.License, "LEADTOOLS.lic"), File.ReadAllText(Path.Combine(rootPath, TheVarSubDir.License, "LEADTOOLS.lic.key"))); // Ocr Engine started IOcrEngine TheOcrEngine = null; OcrEngineType engineType; if (!Enum.TryParse("LEAD", true, out engineType)) { return(null); } if (engineType == OcrEngineType.LEAD) { TheOcrEngine = OcrEngineManager.CreateEngine(engineType, true); TheOcrEngine.Startup(null, null, null, null); TheOcrEngine.SettingManager.SetEnumValue("Recognition.Fonts.DetectFontStyles", 0); TheOcrEngine.SettingManager.SetBooleanValue("Recognition.Fonts.RecognizeFontAttributes", false); if (TheOcrEngine.SettingManager.IsSettingNameSupported("Recognition.RecognitionModuleTradeoff")) { TheOcrEngine.SettingManager.SetEnumValue("Recognition.RecognitionModuleTradeoff", "Accurate"); } } else { TheOcrEngine = OcrEngineManager.CreateEngine(engineType, true); TheOcrEngine.Startup(null, null, null, null); } // initialize RasterCodecs instance RasterCodecs _RasterCodecs = new RasterCodecs(); // initialize DiskMasterFormsRepository instance DiskMasterFormsRepository _DiskMasterFormsRepository = new DiskMasterFormsRepository(_RasterCodecs, Path.Combine(rootPath, TheVarSubDir.OCRMasterFormSets)); var managers = AutoFormsRecognitionManager.Ocr | AutoFormsRecognitionManager.Default; // initialize AutoFormsEngine instance AutoFormsEngine _AutoFormsEngine = new AutoFormsEngine(_DiskMasterFormsRepository, TheOcrEngine, null, managers, 30, 80, false) { UseThreadPool = TheOcrEngine != null && TheOcrEngine.EngineType == OcrEngineType.LEAD }; //============================ // files to be processed string[] _files = GetFiles(Path.Combine(rootPath, TheVarSubDir.OCRInput), FileOrDir); int fileCount = _files.Length; List <string> _FileResults = new List <string>(); // Event to notify us when all work is finished using (AutoResetEvent finishedEvent = new AutoResetEvent(false)) { // Loop through all Files in the given Folder foreach (string _file in _files) { string _FileResult = null; // Process it in a thread ThreadPool.QueueUserWorkItem((state) => { try { // Process it //var _result = _AutoFormsEngine.Run(_file, null).RecognitionResult; // geting error with this statement var imageInfo = _RasterCodecs.GetInformation(_file, true); var targetImage = _RasterCodecs.Load(_file, 0, CodecsLoadByteOrder.Bgr, 1, imageInfo.TotalPages); targetImage.ChangeViewPerspective(RasterViewPerspective.TopLeft); var _result = _AutoFormsEngine.Run(targetImage, null, targetImage, null).RecognitionResult; if (_result == null) { _FileResult = "Not Recognized"; } else { _FileResult = "Successfully Recognized"; } } catch (Exception ex) { _FileResult = "Not Recognized - " + ex.Message; } finally { _FileResults.Add(_FileResult); if (Interlocked.Decrement(ref fileCount) == 0) { // We are done, inform the main thread finishedEvent.Set(); } } }); } // Wait till all operations are finished finishedEvent.WaitOne(); } _AutoFormsEngine.Dispose(); _RasterCodecs.Dispose(); if (TheOcrEngine != null && TheOcrEngine.IsStarted) { TheOcrEngine.Shutdown(); } return(_FileResults); }