Exemplo n.º 1
0
        private void LoadImage(string imageFileName)
        {
            try
            {
                using (var wait = new WaitCursor())
                {
                    // Get the image number of pages
                    int pageCount;
                    using (var imageInfo = _rasterCodecs.GetInformation(imageFileName, true))
                    {
                        pageCount = imageInfo.TotalPages;
                    }

                    // At this point, we can probably load this image, so save it
                    _imageFileName = imageFileName;

                    // See if we can load this image as SVG
                    // If the user selected that and if the format supports it
                    var useSVG = (_demoOptions.UseSVG && _rasterCodecs.CanLoadSvg(imageFileName));

                    // See if we need the virtualizer
                    // If the user selected that and if we have more than one page
                    var useVirtualizer = (_demoOptions.UseVirtiualizer && pageCount > 1);

                    // We are ready
                    // Ensure that the image viewer will not perform any unnecessary calculations in the middle of adding
                    // and removing items
                    _imageViewer.BeginUpdate();

                    try
                    {
                        // Remove the previous pages
                        _imageViewer.Items.Clear();

                        // Set the image info label
                        this.Text            = string.Format("{0} - {1}", imageFileName, Messager.Caption);
                        _imageInfoLabel.Text = string.Format("Pages:{0} - Use SVG:{1} - Use Virtualizer:{2}",
                                                             pageCount, useSVG ? "Yes" : "No", useVirtualizer ? "Yes" : "No");

                        if (useVirtualizer)
                        {
                            LoadPagesWithVirtualizer(imageFileName, pageCount, useSVG);
                        }
                        else
                        {
                            LoadPagesDirect(imageFileName, pageCount, useSVG);
                        }
                    }
                    finally
                    {
                        _imageViewer.EndUpdate();
                    }
                }
            }
            catch (Exception ex)
            {
                Messager.ShowError(this, ex);
            }
        }
Exemplo n.º 2
0
        private void LoadStream(RasterCodecs codec)
        {
            if (stream == null)
            {
                _image = null;
                return;
            }

            CodecsTiffLoadOptions options = codec.Options.Tiff.Load;

            /*
             * codec.Options.Load.Compressed = true;
             */

            //    codec.Options.Load.XResolution = 204;
            //    codec.Options.Load.YResolution = 196;
            //


            CodecsImageInfo info      = codec.GetInformation(stream, true);
            int             firstPage = 1;
            int             lastPage  = info.TotalPages;

            _image = codec.Load(stream, 0, CodecsLoadByteOrder.BgrOrGray, firstPage, lastPage);
        }
Exemplo n.º 3
0
        private void LoadImageList(String fileName, RasterImageList rasterImageList) {

            if (fileName == null || "".Equals(fileName))
            {
                return;
            }
            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException();
            }
            RasterCodecs codec = new RasterCodecs();

            CodecsImageInfo info = codec.GetInformation(fileName,true);

            RasterPaintProperties paintProp = rasterImageList.PaintProperties;
            paintProp.PaintDisplayMode = RasterPaintDisplayModeFlags.ScaleToGray;

            int lastPage = info.TotalPages;
            RasterImage image =codec.Load(fileName,0,CodecsLoadByteOrder.BgrOrGray,1,lastPage);
            rasterImageList.Items.Clear();
            int totalCount = image.PageCount;
            for (int i = 1; i <= totalCount; ++i)
            {
                RasterImageListItem imageItem = new RasterImageListItem(image, i, "Page " + i.ToString());
                rasterImageList.Items.Add(imageItem);

            }

        }
Exemplo n.º 4
0
        private void LoadFile(RasterCodecs codec)
        {
            if (fileName == null || "".Equals(fileName))
            {
                _image = null;
                return;
            }

            CodecsTiffLoadOptions options = codec.Options.Tiff.Load;

            /*
             * codec.Options.Load.Compressed = true;
             */

            //    codec.Options.Load.XResolution = 204;
            //    codec.Options.Load.YResolution = 196;
            //


            CodecsImageInfo info      = codec.GetInformation(fileName, true);
            int             firstPage = 1;
            int             lastPage  = info.TotalPages;

            _image = codec.Load(fileName, 0, CodecsLoadByteOrder.BgrOrGray, firstPage, lastPage);
            //codec.Options.Load.
        }
Exemplo n.º 5
0
        private void LoadFile(RasterCodecs codec)
        {

            if (fileName == null || "".Equals(fileName))
            {
                _image = null;
                return;
            }

            CodecsTiffLoadOptions options = codec.Options.Tiff.Load;

            /*
            codec.Options.Load.Compressed = true;
             */

            //    codec.Options.Load.XResolution = 204;
            //    codec.Options.Load.YResolution = 196;
            //    


            CodecsImageInfo info = codec.GetInformation(fileName, true);
            int firstPage = 1;
            int lastPage = info.TotalPages;
            _image = codec.Load(fileName, 0, CodecsLoadByteOrder.BgrOrGray, firstPage, lastPage);
            //codec.Options.Load.

        }
Exemplo n.º 6
0
        private void LoadImageList()
        {
            if (fileName == null || "".Equals(fileName))
            {
                return;
            }
            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException();
            }
            RasterCodecs codec = new RasterCodecs();

            CodecsImageInfo info = codec.GetInformation(fileName, true);

            RasterPaintProperties paintProp = imageList.PaintProperties;

            paintProp.PaintDisplayMode = RasterPaintDisplayModeFlags.ScaleToGray;

            int lastPage = info.TotalPages;

            image = codec.Load(fileName, 0, CodecsLoadByteOrder.BgrOrGray, 1, lastPage);
            imageList.Items.Clear();
            int totalCount = image.PageCount;

            for (int i = 1; i <= totalCount; ++i)
            {
                RasterImageListItem imageItem = new RasterImageListItem(image, i, "Page " + i.ToString());
                imageList.Items.Add(imageItem);
            }

            LoadCheckBox(totalCount);
        }
Exemplo n.º 7
0
        private void LoadImage(bool loadDefaultImage)
        {
            RasterOpenDialogLoadFormat[] loaderFilters = new RasterOpenDialogLoadFormat[3];
            loaderFilters[0] = new RasterOpenDialogLoadFormat("Bitmap Files (*.dib;*.bmp)", "*.dib;*.bmp");
            loaderFilters[1] = new RasterOpenDialogLoadFormat("TIFF Files (*.tif)", "*.tif");
            loaderFilters[2] = new RasterOpenDialogLoadFormat("All Files (*.tif, *.bmp)", "*.tif;*.bmp");

            ImageFileLoader loader = new ImageFileLoader();

            loader.OpenDialogInitialPath = _openInitialPath;
            loader.Filters = loaderFilters;

            bool bLoaded = false;

            try
            {
                if (loadDefaultImage)
                {
                    bLoaded = loader.Load(this, DemosGlobal.ImagesFolder + @"\ET\dst_rgb_image.tif", _codecs, 1, 1);
                }
                else
                {
                    bLoaded = loader.Load(this, _codecs, true) > 0;
                }

                if (bLoaded)
                {
                    _openInitialPath = Path.GetDirectoryName(loader.FileName);
                    // Resize the image so each dimension becomes a multiple of 4. This is done because it's required by some color spaces
                    int width  = loader.Image.Width;
                    int height = loader.Image.Height;

                    width  += (width % 4 == 0) ? 0 : (4 - (width % 4));
                    height += (height % 4 == 0) ? 0 : (4 - (height % 4));

                    // If the width and the height were the same, the SizeCommand will return immediately.
                    SizeCommand sizeCommand = new SizeCommand(width, height, RasterSizeFlags.None);
                    sizeCommand.Run(loader.Image);

                    CodecsImageInfo info = _codecs.GetInformation(loader.FileName, false, 1);
                    if (info.BitsPerPixel == 24)
                    {
                        _viewer.Image = loader.Image;
                        Text          = "LEADTOOLS for .NET C# Color Conversion Demo";
                    }
                    else
                    {
                        Messager.ShowError(this, "Format not supported\nthis demo supports simple TIFF - (RGB24, CMYK, YCC and LAB) and BMP - (RGB24)");
                    }
                }
            }
            catch (Exception ex)
            {
                Messager.ShowError(this, ex);
            }
            finally
            {
                UpdateMyControls();
            }
        }
Exemplo n.º 8
0
        private void LoadImage(bool loadDefaultImage)
        {
            try
            {
                ImageFileLoader loader  = new ImageFileLoader();
                bool            bLoaded = false;

                if (loadDefaultImage)
                {
                    bLoaded = loader.Load(this, DemosGlobal.ImagesFolder + @"\image1.j2k", _codecs, 1, 1);
                }
                else
                {
                    ImageFileLoader.FilterIndex = 5;
                    bLoaded = loader.Load(this, _codecs, true) > 0;
                }

                if (bLoaded)
                {
                    // Load and set the new image in the viewer
                    _viewer.Image = loader.Image;

                    // Get the information about the image
                    CodecsImageInfo imageInformation = _codecs.GetInformation(loader.FileName, false);
                    switch (imageInformation.Format)
                    {
                    case RasterImageFormat.J2k:
                    case RasterImageFormat.Jp2:
                    case RasterImageFormat.Cmw:
                    {
                        this.Text = String.Format("LEADTOOLS for .NET C# JPEG 2000 Demo {0} X {1}", _viewer.Image.Width, _viewer.Image.Height);
                        break;
                    }

                    default:
                    {
                        this.Text = string.Format("{0} - {1}", loader.FileName, Messager.Caption);
                        break;
                    }
                    }

                    _fileName = loader.FileName;

                    _originalWidth  = imageInformation.Width;
                    _originalHeight = imageInformation.Height;

                    _viewer.Invalidate(true);
                }
            }
            catch (Exception ex)
            {
                Messager.ShowError(this, ex);
            }
            finally
            {
                UpdateMyControls();
            }
        }
Exemplo n.º 9
0
        public bool Load(IWin32Window owner, RasterCodecs codecs, bool autoLoad)
        {
            _fileName = string.Empty;
            _image    = null;

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < LoadFormat.Entries.Length; i++)
            {
                sb.Append(LoadFormat.Entries[i].ToString());
                if (i != (LoadFormat.Entries.Length - 1))
                {
                    sb.Append("|");
                }
            }

            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Filter      = sb.ToString();
            ofd.FilterIndex = _filterIndex;

            bool ok = false;

            try
            {
                if (ofd.ShowDialog(owner) == DialogResult.OK)
                {
                    _fileName = ofd.FileName;
                    ok        = true;

                    _filterIndex = ofd.FilterIndex;

                    CodecsImageInfo info;

                    using (WaitCursor wait = new WaitCursor())
                        info = codecs.GetInformation(ofd.FileName, true);
                    if (autoLoad && ok)
                    {
                        using (WaitCursor wait = new WaitCursor())
                        {
                            _image = codecs.Load(ofd.FileName, 0, CodecsLoadByteOrder.BgrOrGray, 1, 1);
                        }
                    }
                }
                else
                {
                    ok = true;
                }
            }
            catch
            {
                MessageBox.Show("Failed to load image.\nPlease note that, you can't use this dialog to load a DICOM file as an image.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                ok = false;
            }
            return(ok);
        }
Exemplo n.º 10
0
        public HttpResponseMessage CreateFiles(FormDataCollection Form)
        {
            HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, "Some problem in create master form set.");

            try
            {
                if (Form != null)
                {
                    string FileName     = Form["FileName"]?.ToString().Trim() ?? "";
                    string folderName   = Form["FolderName"]?.ToString().Trim() ?? "";
                    string FriendlyName = Form["FriendlyName"]?.ToString().Trim() ?? "";

                    string workingDirectory = HttpContext.Current.Server.MapPath("~/" + RootFolderName + "/" + FriendlyName);
                    string tempDirectory    = HttpContext.Current.Server.MapPath("~/" + RootFolderName + "/temp");
                    string filePath         = tempDirectory + @"\" + FileName;

                    if (Directory.Exists(workingDirectory) && Directory.Exists(tempDirectory) && File.Exists(filePath))
                    {
                        ServiceHelper.SetLicense();
                        RasterImage scannedImage = null;
                        using (RasterCodecs _codecs = new RasterCodecs())
                        {
                            //scannedImage = _codecs.Load(filePath);

                            CodecsImageInfo info           = _codecs.GetInformation(filePath, true);
                            int             infoTotalPages = info.TotalPages;
                            scannedImage = _codecs.Load(filePath, 0, CodecsLoadByteOrder.BgrOrGray, 1, info.TotalPages);
                            DirectoryInfo directoryInfo = new DirectoryInfo(workingDirectory);
                            if (directoryInfo.GetFiles("*").ToList().Count == 0)
                            {
                                CreateMasterForms(scannedImage, workingDirectory, FriendlyName, folderName);
                                File.Delete(filePath);
                                httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, "Master form created successfully.");
                            }
                            else
                            {
                                workingRepository = new DiskMasterFormsRepository(_codecs, workingDirectory);
                                var diskMasterForm = workingRepository?.RootCategory?.MasterForms?.FirstOrDefault();
                                if (diskMasterForm != null)
                                {
                                    AddMasterFormPages(scannedImage, (DiskMasterForm)diskMasterForm, folderName);
                                }
                                File.Delete(filePath);
                                httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, "Page added to master form set successfully.");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, "Some problem in create master form set." + ex.Message.ToString());
            }
            return(httpResponseMessage);
        }
Exemplo n.º 11
0
 private void InitializeFromStream(Stream stream)
 {
     codec = new RasterCodecs();
     codec.Options.Txt.Load.Enabled = true;
     CodecsImageInfo info = codec.GetInformation(stream, true);
     int lastPage = info.TotalPages;
     ImageData = codec.Load(stream, 0, CodecsLoadByteOrder.BgrOrGray, 1, lastPage);
     codec.Options.Load.XResolution = ImageData.XResolution;
     codec.Options.Load.YResolution = ImageData.YResolution;
     LoadTagsMetaData(stream);
 }
Exemplo n.º 12
0
        private static void ConvertPdfToTif(string fileName)
        {
            Func <int, string> getSaveFileName = pg => Path.GetDirectoryName(fileName)
                                                 + Path.DirectorySeparatorChar
                                                 + Path.GetFileNameWithoutExtension(fileName)
                                                 + "_pg"
                                                 + pg.ToString()
                                                 + ".tif";

            try
            {
                using (var codecs = new RasterCodecs())
                {
                    var info = codecs.GetInformation(fileName, true);
                    for (var pageNumber = 1; pageNumber <= info.TotalPages; pageNumber++)
                    {
                        // Make sure the resulting img has the original resolution
                        var pdfInfo = codecs.GetRasterPdfInfo(fileName, pageNumber);
                        codecs.Options.RasterizeDocument.Load.XResolution = pdfInfo.XResolution;
                        codecs.Options.RasterizeDocument.Load.YResolution = pdfInfo.YResolution;

                        // Save the file using a format appropriate for the bits per pixel
                        var bpp        = pdfInfo.BitsPerPixel;
                        var saveFormat = RasterImageFormat.Tif;

                        if (bpp == 1)
                        {
                            saveFormat = RasterImageFormat.CcittGroup4;
                        }
                        else if (bpp > 1 && bpp < 9)
                        {
                            saveFormat = RasterImageFormat.TifLzw;
                        }
                        else if (bpp == 24)
                        {
                            saveFormat = RasterImageFormat.TifJpeg;
                        }

                        using (var page = codecs.Load(fileName, pageNumber))
                            codecs.Save(page, getSaveFileName(pageNumber), saveFormat, 0);
                    }
                }
                Console.WriteLine("Done");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                Console.ReadLine();
            }
        }
Exemplo n.º 13
0
        private void InitializeFromStream(Stream stream)
        {
            codec = new RasterCodecs();
            codec.Options.Txt.Load.Enabled = true;
            CodecsImageInfo info     = codec.GetInformation(stream, true);
            int             lastPage = info.TotalPages;

            ImageData = codec.Load(stream, 0, CodecsLoadByteOrder.BgrOrGray, 1, lastPage);
            codec.Options.Load.XResolution = ImageData.XResolution;
            codec.Options.Load.YResolution = ImageData.YResolution;
            LoadTagsMetaData(stream);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Zoom the image
        /// </summary>
        private void _miZoom_Click(object sender, System.EventArgs e)
        {
            double scaleFactor = _viewer.ScaleFactor;

            if (sender == _miZoomIn)
            {
                if (_originalWidth > _viewer.Image.Width && (scaleFactor == 1))
                {
                    using (RasterCodecs codecs = new RasterCodecs())
                    {
                        CodecsImageInfo _imageInformation = codecs.GetInformation(_fileName, false);
                        switch (_imageInformation.Format)
                        {
                        case RasterImageFormat.J2k:
                            codecs.Options.Jpeg2000.Load.J2kResolution = new LeadSize(_viewer.Image.Width * 2, _viewer.Image.Height * 2);
                            break;

                        case RasterImageFormat.Jp2:
                            codecs.Options.Jpeg2000.Load.Jp2Resolution = new LeadSize(_viewer.Image.Width * 2, _viewer.Image.Height * 2);
                            break;

                        case RasterImageFormat.Cmw:
                            codecs.Options.Jpeg2000.Load.CmwResolution = new LeadSize(_viewer.Image.Width * 2, _viewer.Image.Height * 2);
                            break;
                        }

                        _viewer.Cursor = Cursors.WaitCursor;
                        _viewer.Image.Dispose();
                        _viewer.Image  = codecs.Load(_fileName);
                        this.Text      = String.Format("LEADTOOLS for .NET C# JPEG 2000 Demo {0} X {1}", _viewer.Image.Width, _viewer.Image.Height);
                        _viewer.Cursor = Cursors.Arrow;
                    }
                }
                else
                {
                    scaleFactor *= 2;
                }
            }
            else if (sender == _miZoomOut)
            {
                scaleFactor /= 2;
            }
            else if (sender == _miZoomNormal)
            {
                scaleFactor = 1;
                _viewer.Zoom(ControlSizeMode.None, scaleFactor, _viewer.DefaultZoomOrigin);
            }
            if ((scaleFactor > 0.009) && (scaleFactor < 11))
            {
                _viewer.Zoom(ControlSizeMode.None, scaleFactor, _viewer.DefaultZoomOrigin);
            }
        }
        private void _btnInfo_Click(object sender, EventArgs e)
        {
            if (_lstAttachments.SelectedItems.Count > 0)
            {
                int selectedIndex = _lstAttachments.SelectedIndices[0];
                AttachmentInfoDialog attachmentInfoDlg = new AttachmentInfoDialog();

                string attachmentFileName = _lstAttachments.Items[selectedIndex].Text;

                string tempPath           = Path.GetTempPath();
                string tempAttachmentFile = Path.Combine(Path.GetTempPath(), string.Format("LT_CS_{0}.tmp", attachmentFileName));

                ExtractAttachmentFile(tempAttachmentFile, selectedIndex + 1);

                try
                {
                    using (CodecsImageInfo info = _codecs.GetInformation(tempAttachmentFile, true))
                    {
                        attachmentInfoDlg.InitDialog(attachmentFileName, info);
                        attachmentInfoDlg.ShowDialog(this);
                    }
                }
                catch (Exception ex)
                {
                    Messager.ShowError(this, ex);
                }

                if (File.Exists(tempAttachmentFile))
                {
                    File.Delete(tempAttachmentFile);
                }
            }
            else
            {
                Messager.ShowWarning(this, "No selected attachment!");
            }
        }
        public void InitDialog(string fileName, RasterCodecs codecs)
        {
            _lstAttachments.View = View.Details;
            _fileName            = fileName;
            _codecs = codecs;

            foreach (AttachmentColumnHeader columnHeader in _attachmentColumnHeaders)
            {
                _lstAttachments.Columns.Add(columnHeader._columnName, columnHeader._columnWidth, HorizontalAlignment.Left);
            }

            CodecsAttachments attachments = codecs.ReadAttachments(fileName);
            int attachmentNumber          = 0;

            foreach (CodecsAttachment attachment in attachments)
            {
                attachmentNumber++;
                double fileSize = attachment.FileLength / 1024.0;

                string tempPath           = Path.GetTempPath();
                string tempAttachmentFile = Path.Combine(Path.GetTempPath(), string.Format("LT_CS_{0}.tmp", attachment.FileName));

                ExtractAttachmentFile(tempAttachmentFile, attachmentNumber);

                CodecsImageInfo info = null;
                try
                {
                    info = codecs.GetInformation(tempAttachmentFile, true);
                }
                catch { }

                ListViewItem item = new ListViewItem(new[] { attachment.DisplayName, (info != null) ? ((info.AttachmentCount > 0) ? "Yes" : "No") : "No", attachment.TimeModified.ToString(), (info != null) ? info.IsPortfolio.ToString() : "No", fileSize.ToString("N") + " KB", attachment.Description });
                _lstAttachments.Items.Add(item);

                if (File.Exists(tempAttachmentFile))
                {
                    File.Delete(tempAttachmentFile);
                }

                if (info != null)
                {
                    info.Dispose();
                }
            }
        }
Exemplo n.º 17
0
        //Use this load to load a specific image without showing the open dialog
        public bool Load(IWin32Window owner, string fileName, RasterCodecs codecs, int firstPage, int lastPage)
        {
            _fileName  = fileName;
            _firstPage = firstPage;
            _lastPage  = lastPage;

            using (WaitCursor wait = new WaitCursor())
            {
                using (CodecsImageInfo info = codecs.GetInformation(FileName, true))
                {
                    if (!SetDocumentLoadResultion(codecs, info, firstPage, lastPage))
                    {
                        return(false);
                    }
                }
                _image = codecs.Load(FileName, 0, CodecsLoadByteOrder.BgrOrGray, _firstPage, _lastPage);
            }

            return(true);
        }
Exemplo n.º 18
0
        static MedicalViewerPageInfo[] GetPagesPresentationInfo(DicomDataSet ds, MedicalViewerPageInfo ppiMaster, int DefTotalPages)
        {
            int          nFrames            = DefTotalPages;
            DicomElement elemNumberOfFrames = ds.FindFirstElement(null, DicomTag.NumberOfFrames, true);

            string path = ExtractPDFData(ds);

            if (!string.IsNullOrEmpty(path))
            {
                using (RasterCodecs codecs = new RasterCodecs())
                {
                    using (CodecsImageInfo info = codecs.GetInformation(path, true))
                    {
                        nFrames = info.TotalPages;
                    }
                }
            }
            else
            if (null != elemNumberOfFrames)
            {
                int[] nFramesList = ds.GetIntValue(elemNumberOfFrames, 0, 1);
                nFrames = Math.Max(nFrames, nFramesList[0]);
            }

            List <MedicalViewerPageInfo> PagePresentationInfoLstFromDS = GetPagesInfoFromMaster(ds, ppiMaster);
            List <MedicalViewerPageInfo> PagePresentationInfoLst       = new List <MedicalViewerPageInfo>();

            for (int nIndex = 0; nIndex < nFrames; nIndex++)
            {
                if (nIndex < PagePresentationInfoLstFromDS.Count)
                {
                    PagePresentationInfoLst.Add(PagePresentationInfoLstFromDS[nIndex]);
                }
                else
                {
                    PagePresentationInfoLst.Add(null);
                }
            }

            return(PagePresentationInfoLst.ToArray());
        }
        public ImageDocumentViewModel(Stream stream)
        {
            RasterCodecs codecs = new RasterCodecs();

            codecs.Options.Load.PreferVector = true;
            codecs.Options.Load.AllPages     = true;
            codecs.Options.Load.Resolution   = 72;
            codecs.StartOptimizedLoad();

            CodecsImageInfo imageInfo = codecs.GetInformation(stream, true);

            Pages = new ObservableCollection <PageViewModel>();
            for (int page = 1; page <= imageInfo.TotalPages; page++)
            {
                Pages.Add(new PageViewModel(stream, codecs, page));
            }

            if (imageInfo.TotalPages > 0)
            {
                SetActivePage(1);
            }
        }
Exemplo n.º 20
0
        private bool GetDocumentInformation()
        {
            // Get all the options
            if (!CollectAllOptions())
            {
                return(false);
            }

            // Get the new image information

            string documentPath = _documentPathControl.DocumentPath;

            try
            {
                CodecsImageInfo newImageInfo = null;

                using (WaitCursor wait = new WaitCursor())
                {
                    newImageInfo = _rasterCodecsInstance.GetInformation(documentPath, false);
                }

                // Use this information
                if (_imageInfo != null)
                {
                    _imageInfo.Dispose();
                }

                _imageInfo = newImageInfo;
                _documentInfoControl.SetData(_imageInfo, _rasterCodecsInstance);

                return(true);
            }
            catch (Exception ex)
            {
                Messager.ShowError(this, ex);
                return(false);
            }
        }
        //public AutoFormsRecognizeFormResult ProcessForm(string targetDocPath)
        public AutoFormsRecognizeFormResult ProcessForm(string targetDocPath)
        {
            //load image
            var imageInfo = rasterCodecs.GetInformation(targetDocPath, true);
            var pageCount = imageInfo.TotalPages;
            // var pageCount = 1;


            var targetImage = rasterCodecs.Load(targetDocPath, 0, CodecsLoadByteOrder.Bgr, 1, pageCount);

            //setup engine
            if (!TrySetupAutoFormsEngine())
            {
                throw new Exception("Failed to setup forms auto processing engine.");
            }

            //process image
            targetImage.ChangeViewPerspective(RasterViewPerspective.TopLeft);
            CleanupImage(targetImage, 1, targetImage.PageCount);
            var result = autoEngine.Run(targetImage, null, targetImage, null);

            //var result = autoEngine.Run(targetDocPath, null);

            if (result != null)
            {
                if (result.RecognitionResult.Properties.Pages - targetImage.PageCount > 0)
                {
                    RasterImage remainingPages = rasterCodecs.Load(targetDocPath, 0, CodecsLoadByteOrder.Bgr, pageCount + 1, result.RecognitionResult.Properties.Pages);
                    CleanupImage(remainingPages, 1, remainingPages.PageCount);
                    targetImage.AddPages(remainingPages, 1, -1);
                }

                // log.Debug($"Image processing finished. {Path.GetFileName(targetDocPath)}");
                return(result.RecognitionResult);
            }

            return(null);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Method to ensure that a files that is sent to the service is valid
        /// </summary>
        internal void ValidateFile(Stream s, ref int lastPage)
        {
            try
            {
                using (var codecs = new RasterCodecs())
                    using (var info = codecs.GetInformation(s, true))
                    {
                        //Now that we have the actual file information, we can verify the properties of the file itself.  We will sanitize the lastPage parameter of the request to make sure that it pointing to a valid location within the file.
                        if (lastPage == -1 || lastPage > info.TotalPages)
                        {
                            lastPage = info.TotalPages;
                        }

                        //Check to determine whether or not a file is raster-based, or if it is a document/vector file.  If it is a document/vector file, we can check and see if it is a format that is supposed by calling codecs.LoadSvg
                        if (info.Document.IsDocumentFile || info.Vector.IsVectorFile)
                        {
                            var options = new CodecsLoadSvgOptions {
                                MaximumElements = DemoConfiguration.MaxSvgElements
                            };
                            using (var svg = codecs.LoadSvg(s, 1, options))
                                if (svg == null)
                                {
                                    throw new RejectedFileException();
                                }
                        }
                    }
            }
            //If the file format is not supported by the LEADTOOLS SDK, or if it isn't possible to pull info from the file (such as the case with txt files), the RasterCodecs.GetInformation call will fail.  This will cause the SDK to throw a RasterException -- which we can catch, and then reject the file.
            catch (RasterException)
            {
                throw new RejectedFileException();
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 23
0
        public void Convert(string origFile, string fromFile, string outputDir, string processedDir, string callerRef, string sentTo)
        {
            RasterImage image = null;

            try
            {
                FileInfo fileInfo = new FileInfo(fromFile);
                if (!fileInfo.Exists)
                {
                    _logFile.WriteToLog("Lead Tool Converter - ERROR: " + fromFile + " does not exist.");
                    return;
                }

                string srcFileName = fileInfo.Name;
                _logFile.WriteToLog("Lead Tool Converter: Conversion starting.");
                string srcFileNameWithoutExt = Path.GetFileNameWithoutExtension(srcFileName);
                string outputFileName        = outputDir + @"\" + srcFileNameWithoutExt + "_" + DateTime.Now.ToString("yyyyMMddhh24mmss") + ".tif";


                string fileExt = fileInfo.Extension.ToLower();
                LoadOptionValues(codec, fileExt);
                CodecsImageInfo info = codec.GetInformation(fromFile, true);

                image = codec.Load(fromFile, 0, CodecsLoadByteOrder.Bgr, 1, info.TotalPages);

                codec.Save(image, outputFileName, RasterImageFormat.Tif, 1, 1, info.TotalPages, 1, CodecsSavePageMode.Overwrite);

                _logFile.WriteToLog("Lead Tool Converter: Conversion completed.");
                //jvc insert Inbound - Data Access here
                InboundController ibController = new InboundController();
                ibController._logFile = _logFile;
                _logFile.WriteToLog("InboundController Started: Saving Info to Database for source file:" + origFile + " and converted file: " + outputFileName);
                ibController.ProcessFile(outputFileName, origFile, callerRef, sentTo); //jvc tif and original source format
                if (Properties.Settings.Default.DeleteTIFEnabled)
                {
                    File.Delete(outputFileName);
                }
                _logFile.WriteToLog("InboundController Completed: File Info saved to Database.");
            }
            catch (RasterException ex)
            {
                string erMsg = "";
                if (ex.Code == RasterExceptionCode.FileFormat)
                {
                    erMsg = "The file ''" + fromFile + "'' does not contain an image format recognizable by LEADTOOLS;" + Environment.NewLine + ex.Message;
                }
                else if (ex.Code == RasterExceptionCode.InvalidFormat)
                {
                    erMsg = "The file ''" + fromFile + "'' does not contain an format recognizable by LEADTOOLS;" + Environment.NewLine + ex.Message;
                }
                else
                {
                    erMsg = "Could not load the file ''" + fromFile + "''; " + Environment.NewLine + "Leadtools code:  " + ex.Code + "; message:  " + ex.Message;
                }
                _logFile.WriteToLog(erMsg);
                throw new Exception(erMsg);
            }
            catch (Exception e)
            {
                _logFile.WriteToLog("Lead Tool Converter - ERROR: " + e.Message + "; Stack - " + e.StackTrace);
                throw e;
            }
            finally
            {
                if (image != null)
                {
                    image.Dispose();
                }
            }
        }
Exemplo n.º 24
0
        private void LoadStream(RasterCodecs codec)
        {
            if (stream == null )
            {
                _image = null;
                return;
            }

            CodecsTiffLoadOptions options = codec.Options.Tiff.Load;

            /*
            codec.Options.Load.Compressed = true;
             */

            //    codec.Options.Load.XResolution = 204;
            //    codec.Options.Load.YResolution = 196;
            //    


            CodecsImageInfo info = codec.GetInformation(stream, true);
            int firstPage = 1;
            int lastPage = info.TotalPages;
            _image = codec.Load(stream, 0, CodecsLoadByteOrder.BgrOrGray, firstPage, lastPage);

        }
Exemplo n.º 25
0
        private void _mnuFileSave_Click(object sender, EventArgs e)
        {
            if (_lstImagesInfoMulti == null || _lstImagesInfoMulti.Count <= 0)
            {
                Messager.ShowError(this, "Please Load Files");
                return;
            }

            RasterImage img    = null;
            Cursor      cursor = this.Cursor;

            try
            {
                cursor      = this.Cursor;
                this.Cursor = Cursors.WaitCursor;
                EnableControls(false);

                this._labelConverted.Text = "0";

                if (_saveDialog.ShowDialog() == DialogResult.OK)
                {
                    RasterImageFormat selectedformat = RasterImageFormat.CcittGroup4;
                    if (_saveDialog.FilterIndex == 2)
                    {
                        selectedformat = RasterImageFormat.RasPdfG4;
                    }

                    _szMultiPageFile = _saveDialog.FileName;
                    if (_mnuOptionsSingleRasterImage.Checked)
                    {
                        for (int i = 0; i < _lstImagesInfoMulti.Count; i++)
                        {
                            RasterImage loadedImage = _codecs.Load(_lstImagesInfoMulti[i].Name, 0, CodecsLoadByteOrder.BgrOrGrayOrRomm, 1, -1);
                            if (i == 0)
                            {
                                img = loadedImage;
                            }
                            else
                            {
                                img.AddPages(loadedImage, 1, -1);
                            }

                            _labelConverted.Text = (Convert.ToInt32(_labelConverted.Text) + 1).ToString();
                            Application.DoEvents();
                        }

                        _codecs.Save(img, _szMultiPageFile, selectedformat, 0);

                        img.Dispose();
                    }
                    else
                    {
                        for (int i = 0; i < _lstImagesInfoMulti.Count; i++)
                        {
                            CodecsImageInfo info = _codecs.GetInformation(_lstImagesInfoMulti[i].Name, true);
                            for (int j = 1; j <= info.TotalPages; j++)
                            {
                                img = _codecs.Load(_lstImagesInfoMulti[i].Name, 0, CodecsLoadByteOrder.BgrOrGrayOrRomm, j, j);
                                if (i == 0 && j == 1)
                                {
                                    _codecs.Save(img, _szMultiPageFile, selectedformat, 0, 1, 1, 1, CodecsSavePageMode.Overwrite);
                                }
                                else
                                {
                                    while (!ReadyToAccess(_szMultiPageFile))//Insure File is not inused by other processes
                                    {
                                        Application.DoEvents();
                                    }

                                    _codecs.Save(img, _szMultiPageFile, selectedformat, 0, 1, 1, -1, CodecsSavePageMode.Append);
                                }

                                img.Dispose();
                                Application.DoEvents();
                            }
                            _labelConverted.Text = (Convert.ToInt32(_labelConverted.Text) + 1).ToString();
                            info.Dispose();
                            Application.DoEvents();
                        }
                    }

                    Messager.ShowInformation(this, "Save in MultiPageFile Done");
                }
            }
            catch (Exception ex)
            {
                Messager.ShowError(this, ex);
            }
            finally
            {
                this.Cursor = cursor;
                EnableControls(true);
            }
        }
Exemplo n.º 26
0
        //Use this load to load an image using the open dialog
        public int Load(IWin32Window owner, RasterCodecs codecs, bool autoLoad)
        {
            using (RasterOpenDialog ofd = new RasterOpenDialog(codecs))
            {
                ofd.DereferenceLinks             = true;
                ofd.CheckFileExists              = false;
                ofd.CheckPathExists              = true;
                ofd.EnableSizing                 = true;
                ofd.Filter                       = Filters;
                ofd.FilterIndex                  = _filterIndex;
                ofd.LoadFileImage                = false;
                ofd.LoadOptions                  = false;
                ofd.LoadRotated                  = true;
                ofd.LoadCompressed               = true;
                ofd.LoadMultithreaded            = codecs.Options.Jpeg.Load.Multithreaded;
                ofd.ShowLoadMultithreaded        = true;
                ofd.Multiselect                  = _multiSelect;
                ofd.ShowGeneralOptions           = true;
                ofd.ShowLoadCompressed           = true;
                ofd.ShowLoadOptions              = true;
                ofd.ShowLoadRotated              = true;
                ofd.ShowMultipage                = true;
                ofd.UseGdiPlus                   = UseGdiPlus;
                ofd.ShowPdfOptions               = ShowPdfOptions;
                ofd.ShowXpsOptions               = ShowXpsOptions;
                ofd.ShowXlsOptions               = ShowXlsOptions;
                ofd.ShowRasterizeDocumentOptions = ShowRasterizeDocumentOptions;
                ofd.EnableFileInfoModeless       = true;
                ofd.EnableFileInfoResizing       = true;
                ofd.ShowVffOptions               = ShowVffOptions;
                ofd.ShowAnzOptions               = ShowAnzOptions;
                ofd.ShowVectorOptions            = ShowVectorOptions;
                ofd.ShowPreview                  = true;
                ofd.ShowProgressive              = true;
                ofd.ShowRasterOptions            = true;
                ofd.ShowTotalPages               = true;
                ofd.ShowDeletePage               = true;
                ofd.ShowFileInformation          = true;
                ofd.UseFileStamptoPreview        = true;
                ofd.PreviewWindowVisible         = true;
                ofd.Title         = "LEADTOOLS Open Dialog";
                ofd.FileName      = FileName;
                ofd.LoadCorrupted = LoadCorrupted;
                ofd.PreferVector  = PreferVector;
                if (!String.IsNullOrEmpty(_openDialogInitialPath))
                {
                    ofd.InitialDirectory = _openDialogInitialPath;
                }

                if (ofd.ShowDialog(owner) == DialogResult.OK)
                {
                    foreach (RasterDialogFileData item in ofd.OpenedFileData)
                    {
                        FileName = item.Name;

                        _filterIndex = ofd.FilterIndex;

                        // Set the RasterizeDocument load options before calling GetInformation
                        codecs.Options.RasterizeDocument.Load.PageWidth    = item.Options.RasterizeDocumentOptions.PageWidth;
                        codecs.Options.RasterizeDocument.Load.PageHeight   = item.Options.RasterizeDocumentOptions.PageHeight;
                        codecs.Options.RasterizeDocument.Load.LeftMargin   = item.Options.RasterizeDocumentOptions.LeftMargin;
                        codecs.Options.RasterizeDocument.Load.TopMargin    = item.Options.RasterizeDocumentOptions.TopMargin;
                        codecs.Options.RasterizeDocument.Load.RightMargin  = item.Options.RasterizeDocumentOptions.RightMargin;
                        codecs.Options.RasterizeDocument.Load.BottomMargin = item.Options.RasterizeDocumentOptions.BottomMargin;
                        codecs.Options.RasterizeDocument.Load.Unit         = item.Options.RasterizeDocumentOptions.Unit;
                        codecs.Options.RasterizeDocument.Load.XResolution  = item.Options.RasterizeDocumentOptions.XResolution;
                        codecs.Options.RasterizeDocument.Load.YResolution  = item.Options.RasterizeDocumentOptions.YResolution;
                        codecs.Options.RasterizeDocument.Load.SizeMode     = item.Options.RasterizeDocumentOptions.SizeMode;

                        if (item.FileInfo.Format == RasterImageFormat.Afp || item.FileInfo.Format == RasterImageFormat.Ptoca)
                        {
                            codecs.Options.Ptoka.Load.Resolution = codecs.Options.RasterizeDocument.Load.XResolution;
                        }

                        // Set the user Options
                        codecs.Options.Load.Passes             = item.Passes;
                        codecs.Options.Load.Rotated            = item.LoadRotated;
                        codecs.Options.Load.Compressed         = item.LoadCompressed;
                        codecs.Options.Load.LoadCorrupted      = ofd.LoadCorrupted;
                        codecs.Options.Load.PreferVector       = ofd.PreferVector;
                        codecs.Options.Jpeg.Load.Multithreaded = item.LoadMultithreaded;

                        switch (item.Options.FileType)
                        {
                        case RasterDialogFileOptionsType.Meta:
                        {
                            // Set the user options
                            codecs.Options.Wmf.Load.XResolution = item.Options.MetaOptions.XResolution;
                            codecs.Options.Wmf.Load.YResolution = item.Options.MetaOptions.XResolution;
                            break;
                        }

                        case RasterDialogFileOptionsType.Pdf:
                        {
                            if (codecs.Options.Pdf.Load.UsePdfEngine)
                            {
                                // Set the user options
                                codecs.Options.Pdf.Load.DisplayDepth  = item.Options.PdfOptions.DisplayDepth;
                                codecs.Options.Pdf.Load.GraphicsAlpha = item.Options.PdfOptions.GraphicsAlpha;
                                codecs.Options.Pdf.Load.TextAlpha     = item.Options.PdfOptions.TextAlpha;
                                codecs.Options.Pdf.Load.UseLibFonts   = item.Options.PdfOptions.UseLibFonts;
                            }

                            break;
                        }

                        case RasterDialogFileOptionsType.Misc:
                        {
                            switch (item.FileInfo.Format)
                            {
                            case RasterImageFormat.Jbig:
                            {
                                // Set the user options
                                codecs.Options.Jbig.Load.Resolution = new LeadSize(item.Options.MiscOptions.XResolution,
                                                                                   item.Options.MiscOptions.YResolution);
                                break;
                            }

                            case RasterImageFormat.Cmw:
                            {
                                // Set the user options
                                codecs.Options.Jpeg2000.Load.CmwResolution = new LeadSize(item.Options.MiscOptions.XResolution,
                                                                                          item.Options.MiscOptions.YResolution);
                                break;
                            }

                            case RasterImageFormat.Jp2:
                            {
                                // Set the user options
                                codecs.Options.Jpeg2000.Load.Jp2Resolution = new LeadSize(item.Options.MiscOptions.XResolution,
                                                                                          item.Options.MiscOptions.YResolution);
                                break;
                            }

                            case RasterImageFormat.J2k:
                            {
                                // Set the user options
                                codecs.Options.Jpeg2000.Load.J2kResolution = new LeadSize(item.Options.MiscOptions.XResolution,
                                                                                          item.Options.MiscOptions.YResolution);
                                break;
                            }
                            }

                            break;
                        }

                        case RasterDialogFileOptionsType.Xls:
                        {
                            // Set the user options
                            codecs.Options.Xls.Load.MultiPageSheet  = item.Options.XlsOptions.MultiPageSheet;
                            codecs.Options.Xls.Load.ShowHiddenSheet = item.Options.XlsOptions.ShowHiddenSheet;
#if LEADTOOLS_V20_OR_LATER
                            codecs.Options.Xls.Load.MultiPageUseSheetWidth = item.Options.XlsOptions.MultiPageUseSheetWidth;
                            codecs.Options.Xls.Load.PageOrderDownThenOver  = item.Options.XlsOptions.PageOrderDownThenOver;
                            codecs.Options.Xls.Load.MultiPageEnableMargins = item.Options.XlsOptions.MultiPageEnableMargins;
#endif //#if LEADTOOLS_V20_OR_LATER
                        }
                        break;

                        case RasterDialogFileOptionsType.Vff:
                        {
                            codecs.Options.Vff.Load.View = item.Options.VffOptions.View;
                            break;
                        }

                        case RasterDialogFileOptionsType.Anz:
                        {
                            codecs.Options.Anz.Load.View = item.Options.AnzOptions.View;
                            break;
                        }

                        case RasterDialogFileOptionsType.Vector:
                        {
                            codecs.Options.Vector.Load.BackgroundColor      = item.Options.VectorOptions.Options.BackgroundColor;
                            codecs.Options.Vector.Load.BitsPerPixel         = item.Options.VectorOptions.Options.BitsPerPixel;
                            codecs.Options.Vector.Load.ForceBackgroundColor = item.Options.VectorOptions.Options.ForceBackgroundColor;
                            codecs.Options.Vector.Load.ViewHeight           = item.Options.VectorOptions.Options.ViewHeight;
                            codecs.Options.Vector.Load.ViewMode             = item.Options.VectorOptions.Options.ViewMode;
                            codecs.Options.Vector.Load.ViewWidth            = item.Options.VectorOptions.Options.ViewWidth;
                            break;
                        }
                        }

                        int firstPage = 1;
                        int lastPage  = 1;
                        int infoTotalPages;

                        CodecsImageInfo info = null;

                        using (WaitCursor wait = new WaitCursor())
                        {
                            info           = codecs.GetInformation(FileName, true);
                            infoTotalPages = info.TotalPages;
                        }

                        if (_showLoadPagesDialog)
                        {
                            firstPage = 1;
                            lastPage  = infoTotalPages;

                            if (firstPage != lastPage)
                            {
                                using (ImageFileLoaderPagesDialog dlg = new ImageFileLoaderPagesDialog(infoTotalPages, LoadOnlyOnePage))
                                {
                                    if (dlg.ShowDialog(owner) == DialogResult.OK)
                                    {
                                        firstPage = dlg.FirstPage;
                                        lastPage  = dlg.LastPage;
                                    }
                                    else
                                    {
                                        if (info != null)
                                        {
                                            info.Dispose();
                                        }
                                        return(0);
                                    }
                                }
                            }
                        }
                        else
                        {
                            firstPage = item.PageNumber;
                            lastPage  = item.PageNumber;
                        }

                        _firstPage = firstPage;
                        _lastPage  = lastPage;

                        if (!SetDocumentLoadResultion(codecs, info, firstPage, lastPage))
                        {
                            info.Dispose();
                            return(0);
                        }

                        if (autoLoad)
                        {
                            using (WaitCursor wait = new WaitCursor())
                            {
                                _image = codecs.Load(FileName, 0, CodecsLoadByteOrder.BgrOrGray, firstPage, lastPage);
                                if (codecs.LoadStatus != RasterExceptionCode.Success)
                                {
                                    String message = String.Format("The image was only partially loaded due to error: {0}", codecs.LoadStatus.ToString());
                                    Messager.Show(null, message, MessageBoxIcon.Information, MessageBoxButtons.OK);
                                }
                                if (_image != null)
                                {
                                    _image.CustomData.Add("IsBigTiff", info.Tiff.IsBigTiff);
                                    _images.Add(new ImageInformation(_image, item.Name));
                                }
                            }
                        }
                        info.Dispose();
                    }
                }

                return(ofd.OpenedFileData.Count);
            }
        }
Exemplo n.º 27
0
        private string DoTheConvert(string sourceImage, string actionProfile, string annotate, ReturnPath retPath)
        {
            string strRetFile = "";

            strActionProfile = actionProfile;
            strAnnotate      = annotate;
            this.sourceImage = sourceImage;

            try
            {
                RasterCodecs.Startup();
                RasterSupport.Unlock(RasterSupportType.Pro, "LhwcFdF3jN");
                bool isLocked = RasterSupport.IsLocked(RasterSupportType.Pro);
                rasterCodecs = new RasterCodecs();
                imageInfo    = rasterCodecs.GetInformation(sourceImage, true);
                if (imageInfo.TotalPages > 0 && imageInfo.Format == Leadtools.RasterImageFormat.Gif)
                {
                    rasterCodecs.Options.Gif.Load.AnimationLoop    = imageInfo.Gif.AnimationLoop;
                    rasterCodecs.Options.Gif.Save.AnimationLoop    = imageInfo.Gif.AnimationLoop;
                    rasterCodecs.Options.Gif.Save.UseAnimationLoop = imageInfo.Gif.HasAnimationLoop;

                    if (imageInfo.Gif.HasAnimationBackground)
                    {
                        rasterCodecs.Options.Gif.Save.AnimationBackground = imageInfo.Gif.AnimationBackground;
                    }
                    rasterCodecs.Options.Gif.Save.UseAnimationBackground = imageInfo.Gif.HasAnimationBackground;
                    // #1.0.5.0

                    if (imageInfo.Gif.HasAnimationPalette)
                    {
                        rasterCodecs.Options.Gif.Save.SetAnimationPalette(imageInfo.Gif.GetAnimationPalette());
                    }
                    rasterCodecs.Options.Gif.Save.UseAnimationPalette = imageInfo.Gif.HasAnimationPalette;

                    rasterCodecs.Options.Gif.Save.AnimationWidth  = imageInfo.Gif.AnimationWidth;
                    rasterCodecs.Options.Gif.Save.AnimationHeight = imageInfo.Gif.AnimationHeight;
                }
                img = rasterCodecs.Load(sourceImage);

                // Load convert action profile
                if (Init(sourceImage, strActionProfile))
                {
                    // loop on actions
                    LoopActions();
                    SaveImage();

                    // add a copyright or something like this to the image
                    if (xmlActionProfile.SelectSingleNode("//root/actionProfile[@ID='" + strActionProfile + "']/action[@ID='annotate']") != null && strTargetImage.Length > 0)
                    {
                        Annotate();
                    }

                    if (retPath == ReturnPath.AbsPath)
                    {
                        strRetFile = strTargetImage;
                    }
                    else if (retPath == ReturnPath.Url)
                    {
                        strRetFile = strTargetImageUrl;
                    }
                }
            }

            finally
            {
                img.Dispose();
                RasterCodecs.Shutdown();
            }

            return(strRetFile);
        }
Exemplo n.º 28
0
        /// <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 ImageInfo Info(Uri uri, int pageNumber = 1)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            if (pageNumber < 0)
            {
                throw new ArgumentOutOfRangeException("pageNumber", "must be a value greater than or equal to 0");
            }

            var page = pageNumber;

            // Default is page 1
            if (page == 0)
            {
                page = 1;
            }

            // Use a temp file, much faster than calling Load/Info from a URI directly
            // In a production service, you might want to create a caching mechanism
            string tempFile = Path.GetTempFileName();

            try
            {
                // Force the uri to be fully qualified, reject everything else for security reasons
                if (uri.IsFile || uri.IsUnc)
                {
                    throw new ArgumentException("URL cannot be local file or UNC path.");
                }

                // Download the file
                if (File.Exists(HttpContext.Current.Server.MapPath("~/" + uri.LocalPath.ToString())))
                {
                    using (WebClient client = new WebClient())
                        client.DownloadFile(uri, tempFile);
                }
                else
                {
                    ImageInfo imginfo = new ImageInfo();
                    return(imginfo);
                    //throw new FileNotFoundException("Master set detail does not exists.");
                }

                using (RasterCodecs codecs = new RasterCodecs())
                {
                    // Initialize the options for RasterCodecs
                    ServiceHelper.InitCodecs(codecs, 0);

                    using (CodecsImageInfo info = codecs.GetInformation(tempFile, true, page))
                    {
                        ImageInfo imageInfo = new ImageInfo();
                        imageInfo.Uri             = uri.ToString();
                        imageInfo.FormatId        = (int)info.Format;
                        imageInfo.FormatName      = info.Format.ToString();
                        imageInfo.MimeType        = RasterCodecs.GetMimeType(info.Format);
                        imageInfo.Width           = info.Width;
                        imageInfo.Height          = info.Height;
                        imageInfo.BitsPerPixel    = info.BitsPerPixel;
                        imageInfo.BytesPerLine    = info.BytesPerLine;
                        imageInfo.SizeDisk        = info.SizeDisk;
                        imageInfo.SizeMemory      = info.SizeMemory;
                        imageInfo.Compression     = info.Compression;
                        imageInfo.ViewPerspective = GetViewPerspectiveName(info.ViewPerspective);
                        imageInfo.Order           = info.Order.ToString();
                        imageInfo.ColorSpace      = info.ColorSpace.ToString();
                        imageInfo.PageNumber      = info.PageNumber;
                        imageInfo.TotalPages      = info.TotalPages;
                        imageInfo.HasResolution   = info.HasResolution;
                        imageInfo.XResolution     = info.XResolution;
                        imageInfo.YResolution     = info.YResolution;
                        imageInfo.IsRotated       = info.IsRotated;
                        imageInfo.IsSigned        = info.IsSigned;
                        imageInfo.HasAlpha        = info.HasAlpha;

                        imageInfo.BrowserCompatible = false;

                        switch (info.Format)
                        {
                        case RasterImageFormat.Png:
                        case RasterImageFormat.Gif:
                        case RasterImageFormat.Jpeg:
                        case RasterImageFormat.Jpeg411:
                        case RasterImageFormat.Jpeg422:
                        case RasterImageFormat.JpegLab:
                        case RasterImageFormat.JpegLab411:
                        case RasterImageFormat.JpegLab422:
                        case RasterImageFormat.JpegRgb:
                            imageInfo.BrowserCompatible = true;
                            break;

                        default:
                            break;
                        }

                        return(imageInfo);
                    }
                }
            }

            catch (Exception ex)
            {
                Log(string.Format("Info - Error:{1}{0}TempFile:{2}{0}Uri:{3}, PageNumber:{4}", Environment.NewLine, ex.Message, tempFile, uri, page));
                throw;
            }
            finally
            {
                if (File.Exists(tempFile))
                {
                    try
                    {
                        File.Delete(tempFile);
                    }
                    catch { }
                }
            }
        }
Exemplo n.º 30
0
        public bool Load(IWin32Window owner, RasterCodecs codecs, bool autoLoad)
        {
#if LEADTOOLS_V16_OR_LATER && !LEADTOOLS_V17_OR_LATER
            // Load using the RasterizeDocument options
            codecs.Options.RasterizeDocument.Load.Enabled = true;
#endif

            RasterOpenDialog ofd = new RasterOpenDialog(codecs);

            ofd.DereferenceLinks      = true;
            ofd.CheckFileExists       = false;
            ofd.CheckPathExists       = true;
            ofd.EnableSizing          = true;
            ofd.Filter                = Filters;
            ofd.FilterIndex           = _filterIndex;
            ofd.LoadFileImage         = false;
            ofd.LoadOptions           = false;
            ofd.LoadRotated           = true;
            ofd.LoadCompressed        = true;
            ofd.Multiselect           = false;
            ofd.ShowGeneralOptions    = true;
            ofd.ShowLoadCompressed    = true;
            ofd.ShowLoadOptions       = true;
            ofd.ShowLoadRotated       = true;
            ofd.ShowMultipage         = true;
            ofd.ShowPdfOptions        = true;
            ofd.ShowPreview           = true;
            ofd.ShowProgressive       = true;
            ofd.ShowRasterOptions     = true;
            ofd.ShowTotalPages        = true;
            ofd.ShowDeletePage        = true;
            ofd.ShowFileInformation   = true;
            ofd.UseFileStamptoPreview = true;
            ofd.PreviewWindowVisible  = true;
            ofd.Title    = "LEADTOOLS Open Dialog";
            ofd.FileName = FileName;
#if LEADTOOLS_V16_OR_LATER
            ofd.ShowRasterizeDocumentOptions = true;
            ofd.ShowXlsOptions = true;
#endif
            bool ok = false;

            if (ofd.ShowDialog(owner) == DialogResult.OK)
            {
                RasterDialogFileData firstItem = ofd.OpenedFileData[0] as RasterDialogFileData;
                FileName = firstItem.Name;

                ok = true;

                _filterIndex = ofd.FilterIndex;

                CodecsImageInfo info;

                using (WaitCursor wait = new WaitCursor())
                    info = codecs.GetInformation(FileName, true);

                if (info.Format == RasterImageFormat.RasPdf ||
                    info.Format == RasterImageFormat.RasPdfG31Dim ||
                    info.Format == RasterImageFormat.RasPdfG32Dim ||
                    info.Format == RasterImageFormat.RasPdfG4 ||
                    info.Format == RasterImageFormat.RasPdfJpeg ||
                    info.Format == RasterImageFormat.RasPdfJpeg422 ||
                    info.Format == RasterImageFormat.RasPdfJpeg411)
                {
                    if (!codecs.Options.Pdf.IsEngineInstalled)
                    {
#if !LEADTOOLS_V17_OR_LATER
                        PdfEngineDialog dlg = new PdfEngineDialog();
                        if (dlg.ShowDialog(owner) != DialogResult.OK)
                        {
                            return(false);
                        }
#endif
                    }
                }

#if LEADTOOLS_V16_OR_LATER
                // Set the RasterizeDocument load options before calling GetInformation
#if !LEADTOOLS_V17_OR_LATER
                codecs.Options.RasterizeDocument.Load.Enabled = firstItem.Options.RasterizeDocumentOptions.Enabled;
#endif
                codecs.Options.RasterizeDocument.Load.PageWidth    = firstItem.Options.RasterizeDocumentOptions.PageWidth;
                codecs.Options.RasterizeDocument.Load.PageHeight   = firstItem.Options.RasterizeDocumentOptions.PageHeight;
                codecs.Options.RasterizeDocument.Load.LeftMargin   = firstItem.Options.RasterizeDocumentOptions.LeftMargin;
                codecs.Options.RasterizeDocument.Load.TopMargin    = firstItem.Options.RasterizeDocumentOptions.TopMargin;
                codecs.Options.RasterizeDocument.Load.RightMargin  = firstItem.Options.RasterizeDocumentOptions.RightMargin;
                codecs.Options.RasterizeDocument.Load.BottomMargin = firstItem.Options.RasterizeDocumentOptions.BottomMargin;
                codecs.Options.RasterizeDocument.Load.Unit         = firstItem.Options.RasterizeDocumentOptions.Unit;
                codecs.Options.RasterizeDocument.Load.XResolution  = firstItem.Options.RasterizeDocumentOptions.XResolution;
                codecs.Options.RasterizeDocument.Load.YResolution  = firstItem.Options.RasterizeDocumentOptions.YResolution;
                codecs.Options.RasterizeDocument.Load.SizeMode     = firstItem.Options.RasterizeDocumentOptions.SizeMode;
#endif

                // Set the user Options
                codecs.Options.Load.Passes     = firstItem.Passes;
                codecs.Options.Load.Rotated    = firstItem.LoadRotated;
                codecs.Options.Load.Compressed = firstItem.LoadCompressed;
                _FileFormatType = firstItem.Options.FileType;

                switch (firstItem.Options.FileType)
                {
                case RasterDialogFileOptionsType.Meta:
                {
                    // Set the user options
                    codecs.Options.Wmf.Load.XResolution = firstItem.Options.MetaOptions.XResolution;
                    codecs.Options.Wmf.Load.YResolution = firstItem.Options.MetaOptions.XResolution;

                    break;
                }

                case RasterDialogFileOptionsType.Pdf:
                {
                    if (codecs.Options.Pdf.IsEngineInstalled)
                    {
#if !LEADTOOLS_V175_OR_LATER
                        if (!_firstPdfLoaded)
                        {
                            PdfDPIOptions DPIOptions = new PdfDPIOptions();

                            if (DPIOptions.ShowDialog() == DialogResult.OK)
                            {
                                codecs.Options.Pdf.Load.XResolution = DPIOptions.XResolution;
                                codecs.Options.Pdf.Load.YResolution = DPIOptions.YResolution;
                                _firstPdfLoaded = true;
                            }
                            else
                            {
                                codecs.Options.Pdf.Load.XResolution = 150;
                                codecs.Options.Pdf.Load.YResolution = 150;
                            }
                        }
                        else
                        {
                            // Set the user options
                            codecs.Options.Pdf.Load.DisplayDepth  = firstItem.Options.PdfOptions.DisplayDepth;
                            codecs.Options.Pdf.Load.GraphicsAlpha = firstItem.Options.PdfOptions.GraphicsAlpha;
                            codecs.Options.Pdf.Load.TextAlpha     = firstItem.Options.PdfOptions.TextAlpha;
                            codecs.Options.Pdf.Load.UseLibFonts   = firstItem.Options.PdfOptions.UseLibFonts;
                        }
#endif
                    }

                    break;
                }

                case RasterDialogFileOptionsType.Misc:
                {
                    switch (firstItem.FileInfo.Format)
                    {
                    case RasterImageFormat.Jbig:
                    {
                        // Set the user options
                        codecs.Options.Jbig.Load.Resolution = new LeadSize(firstItem.Options.MiscOptions.XResolution,
                                                                           firstItem.Options.MiscOptions.YResolution);
                        break;
                    }

                    case RasterImageFormat.Cmw:
                    {
                        // Set the user options
                        codecs.Options.Jpeg2000.Load.CmwResolution = new LeadSize(firstItem.Options.MiscOptions.XResolution,
                                                                                  firstItem.Options.MiscOptions.YResolution);
                        break;
                    }

                    case RasterImageFormat.Jp2:
                    {
                        // Set the user options
                        codecs.Options.Jpeg2000.Load.Jp2Resolution = new LeadSize(firstItem.Options.MiscOptions.XResolution,
                                                                                  firstItem.Options.MiscOptions.YResolution);
                        break;
                    }

                    case RasterImageFormat.J2k:
                    {
                        // Set the user options
                        codecs.Options.Jpeg2000.Load.J2kResolution = new LeadSize(firstItem.Options.MiscOptions.XResolution,
                                                                                  firstItem.Options.MiscOptions.YResolution);
                        break;
                    }
                    }

                    break;
                }
                }

                int firstPage = 1;
                int lastPage  = 1;

                if (ShowLoadPagesDialog)
                {
                    firstPage = 1;
                    lastPage  = info.TotalPages;

                    if (firstPage != lastPage)
                    {
                        ImageFileLoaderPagesDialog dlg = new ImageFileLoaderPagesDialog(info.TotalPages, LoadOnlyOnePage);
                        if (dlg.ShowDialog(owner) == DialogResult.OK)
                        {
                            firstPage = dlg.FirstPage;
                            lastPage  = dlg.LastPage;
                        }
                        else
                        {
                            ok = false;
                        }
                    }
                }
                else
                {
                    firstPage = firstItem.PageNumber;
                    lastPage  = firstItem.PageNumber;
                }

                _firstPage = firstPage;
                _lastPage  = lastPage;

                if (autoLoad && ok)
                {
                    using (WaitCursor wait = new WaitCursor())
                    {
                        _image = codecs.Load(FileName, 0, CodecsLoadByteOrder.BgrOrGray, firstPage, lastPage);
                    }
                }
            }

            return(ok);
        }
Exemplo n.º 31
0
        private void LoadDocument(string fileName, bool loadDefault)
        {
            try
            {
                using (RasterCodecs codecs = new RasterCodecs())
                {
                    // Set load resolution
                    codecs.Options.RasterizeDocument.Load.XResolution = 300;
                    codecs.Options.RasterizeDocument.Load.YResolution = 300;

                    int firstPage = 1;
                    int lastPage  = 1;
                    List <SvgDocument> documents = new List <SvgDocument>();

                    if (!loadDefault)
                    {
                        // Check if the file can be loaded as svg
                        bool canLoadSvg = codecs.CanLoadSvg(fileName);
                        using (CodecsImageInfo info = codecs.GetInformation(fileName, true))
                        {
                            if (!canLoadSvg)
                            {
                                // Check if the file type is not PDF
                                if (info.Format != RasterImageFormat.PdfLeadMrc &&
                                    info.Format != RasterImageFormat.RasPdf &&
                                    info.Format != RasterImageFormat.RasPdfCmyk &&
                                    info.Format != RasterImageFormat.RasPdfG31Dim &&
                                    info.Format != RasterImageFormat.RasPdfG32Dim &&
                                    info.Format != RasterImageFormat.RasPdfG4 &&
                                    info.Format != RasterImageFormat.RasPdfJbig2 &&
                                    info.Format != RasterImageFormat.RasPdfJpeg &&
                                    info.Format != RasterImageFormat.RasPdfJpeg411 &&
                                    info.Format != RasterImageFormat.RasPdfJpeg422 &&
                                    info.Format != RasterImageFormat.RasPdfJpx &&
                                    info.Format != RasterImageFormat.RasPdfLzw &&
                                    info.Format != RasterImageFormat.RasPdfLzwCmyk)
                                {
                                    MessageBox.Show("The selected file can't be loaded as an SVG file", "Invalid File Format", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    return;
                                }
                            }

                            if (info.TotalPages > 1)
                            {
                                using (ImageFileLoaderPagesDialog dlg = new ImageFileLoaderPagesDialog(info.TotalPages, false))
                                {
                                    if (dlg.ShowDialog(this) == DialogResult.Cancel)
                                    {
                                        return;
                                    }

                                    firstPage = dlg.FirstPage;
                                    lastPage  = dlg.LastPage;
                                }
                            }
                        }
                    }

                    using (WaitCursor wait = new WaitCursor())
                    {
                        for (int page = firstPage; page <= lastPage; page++)
                        {
                            SvgDocument svgDoc = codecs.LoadSvg(fileName, page, _loadSvgOptions) as SvgDocument;
                            documents.Add(svgDoc);
                        }

                        SetDocument(fileName, documents, firstPage);
                    }

                    UpdateControls();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, string.Format("Error {0}{1}{2}", ex.GetType().FullName, Environment.NewLine, ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
Exemplo n.º 32
0
        /// <summary>
        /// Run the load command.
        /// </summary>
        /// <param name="id">Scanning session id.</param>
        /// <param name="service">Twain scanning service handle.</param>
        /// <param name="args">Load command arguments.</param>
        public static void Run(string id, TwainScanningService service, LoadCommandArgs args)
        {
            if (args.Uri == null)
            {
                throw new ArgumentNullException("Uri");
            }
            if (args.StartPage < 0)
            {
                throw new ArgumentOutOfRangeException("StartPage", "must be a value greater than or equal to 1");
            }

            if (args.Resolution < 0)
            {
                throw new ArgumentOutOfRangeException("Resolution", "must be a value greater than or equals to 0");
            }

            // Force the uri to be fully qualified, reject everything else for security reasons
            if (args.Uri.IsFile || args.Uri.IsUnc)
            {
                throw new ArgumentException("URL cannot be local file or UNC path.");
            }

            // Use a temp file, much faster than calling Load/Info from a URI directly
            // In a production service, you might want to create a caching mechanism
            string tempFile = Path.GetTempFileName();

            try
            {
                // Download the file
                using (WebClient client = new WebClient())
                    client.DownloadFile(args.Uri, tempFile);

                using (RasterCodecs codecs = new RasterCodecs())
                {
                    DemoUtils.InitCodecs(codecs, args.Resolution);

                    CodecsImageInfo info = codecs.GetInformation(tempFile, true);

                    if ((args.EndPage < 0) || (args.EndPage > info.TotalPages))
                    {
                        args.EndPage = info.TotalPages;
                    }

                    for (int pageNumber = args.StartPage; pageNumber <= args.EndPage; pageNumber++)
                    {
                        using (RasterImage image = codecs.Load(tempFile, args.BitsPerPixel, CodecsLoadByteOrder.BgrOrGray, pageNumber, pageNumber))
                        {
                            service.AddPage(id, image);
                        }
                    }
                }
            }
            finally
            {
                if (File.Exists(tempFile))
                {
                    try
                    {
                        File.Delete(tempFile);
                    }
                    catch
                    {
                        // Do nothing.
                    }
                }
            }
        }
Exemplo n.º 33
0
        private void ThreadProc(object stateInfo)
        {
            WorkItemData data                = (WorkItemData)stateInfo;
            IOcrEngine   ocrEngine           = null;
            bool         passedCriticalStage = false;

            try
            {
                // See if we have canceled
                lock (_abortedLockObject)
                {
                    if (_aborted)
                    {
                        return;
                    }
                }

                string destinationFile = Path.Combine(data.DestinationDirectory, Path.GetFileName(data.SourceFile));

                ocrEngine = data.OcrEngine;

                lock (_abortedLockObject)
                {
                    if (_aborted)
                    {
                        return;
                    }
                }

                // Convert this image file to a document
                string extension = DocumentWriter.GetFormatFileExtension(data.Format);
                destinationFile = string.Concat(destinationFile, ".", extension);
                if (data.Format == DocumentFormat.Ltd && File.Exists(destinationFile))
                {
                    File.Delete(destinationFile);
                }

                string sourceFile = Path.GetFileName(data.SourceFile);

                try
                {
                    // Create a document and add the pages
                    using (IOcrDocument ocrDocument = ocrEngine.DocumentManager.CreateDocument(null, OcrCreateDocumentOptions.AutoDeleteFile))
                    {
                        // Get the image number of pages
                        int imagePageCount;

                        RasterCodecs codecs = ocrDocument.RasterCodecsInstance;

                        using (CodecsImageInfo imageInfo = codecs.GetInformation(data.SourceFile, true))
                        {
                            long maximumMemorySize            = 42187;
                            IOcrSettingManager settingManager = ocrEngine.SettingManager;

                            // Get the maximum size of the bitmap from the setting
                            if (settingManager.IsSettingNameSupported("Recognition.MaximumPageConventionalMemorySize"))
                            {
                                int maximumConventionalMemorySize = settingManager.GetIntegerValue("Recognition.MaximumPageConventionalMemorySize");
                                maximumMemorySize = (long)maximumConventionalMemorySize * 1024;
                            }

                            SetRecommendedLoadingOptions(codecs, imageInfo, maximumMemorySize);

                            imagePageCount = imageInfo.TotalPages;
                        }

                        // Set the DocumentWriter options
                        using (MemoryStream ms = new MemoryStream(data.DocumentWriterOptions))
                        {
                            ocrDocument.DocumentWriterInstance.LoadOptions(ms);
                        }

                        passedCriticalStage = true;

                        //recognize and add pages
                        for (int pageNumber = 1; pageNumber <= imagePageCount; pageNumber++)
                        {
                            lock (_abortedLockObject)
                            {
                                if (_aborted)
                                {
                                    return;
                                }
                            }

                            var image = codecs.Load(data.SourceFile, pageNumber);

                            using (var ocrPage = ocrEngine.CreatePage(image, OcrImageSharingMode.AutoDispose))
                            {
                                ocrPage.Recognize(null);
                                ocrDocument.Pages.Add(ocrPage);
                            }
                        }

                        // Save
                        ocrDocument.Save(destinationFile, data.Format, null);
                    }
                }
                finally
                {
                }

                OnSuccess(destinationFile);
            }
            catch (Exception ex)
            {
                string message;

                if (passedCriticalStage && data.FirstTry)
                {
                    message = string.Format("Error '{0}' while converting file '{1}' (first time, quarantined)", ex.Message, data.SourceFile);
                    AddToQuarantine(data.SourceFile);
                }
                else if (passedCriticalStage && !data.FirstTry)
                {
                    message = string.Format("Error '{0}' while converting file '{1}' (quarantined error)", ex.Message, data.SourceFile);
                }
                else
                {
                    message = string.Format("Error '{0}' while converting file '{1}'", ex.Message, data.SourceFile);
                }

                OnError(message);
            }
            finally
            {
                if (ocrEngine != null && ocrEngine != data.OcrEngine)
                {
                    ocrEngine.Dispose();
                }

                if (Interlocked.Decrement(ref _workItemCount) == 0)
                {
                    _batchFinishedEvent.Set();
                }
            }
        }
        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);
        }
Exemplo n.º 35
0
        private void LoadImageList()
        {
            if (fileName == null || "".Equals(fileName))
            {
                return;
            }
            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException("An error occurred while loading the image list." + Environment.NewLine +
                    "Error CNF-543 in " + FORM_NAME + ".LoadImageList()");
            }

            RasterCodecs codec = new RasterCodecs();

            CodecsImageInfo info = codec.GetInformation(fileName, true);

            RasterPaintProperties paintProp = imageList.PaintProperties;
            paintProp.PaintDisplayMode = RasterPaintDisplayModeFlags.ScaleToGray;

            int lastPage = info.TotalPages;
            image = codec.Load(fileName, 0, CodecsLoadByteOrder.BgrOrGray, 1, lastPage);
            imageList.Items.Clear();
            int totalCount = image.PageCount;
            for (int i = 1; i <= totalCount; ++i)
            {
                RasterImageListItem imageItem = new RasterImageListItem(image, i, "Page " + i.ToString());
                imageList.Items.Add(imageItem);

            }

            LoadCheckBox(totalCount);
        }