Exemple #1
0
        /// <summary>
        /// Called by the owner to initialize
        /// </summary>
        public void SetData(RasterCodecs rasterCodecsInstance)
        {
            // First fill the controls with possible values

            _displayDepthComboBox.Items.Add(new Tools.ValueNameItem <int>(1, "1 bits per pixel"));
            _displayDepthComboBox.Items.Add(new Tools.ValueNameItem <int>(4, "4 bits per pixel"));
            _displayDepthComboBox.Items.Add(new Tools.ValueNameItem <int>(8, "8 bits per pixel"));
            _displayDepthComboBox.Items.Add(new Tools.ValueNameItem <int>(24, "24 bits per pixel"));

            _textAlphaComboBox.Items.Add(new Tools.ValueNameItem <int>(1, "Do not use font anti-aliasing"));
            _textAlphaComboBox.Items.Add(new Tools.ValueNameItem <int>(2, "Use 2-bit font anti-aliasing"));
            _textAlphaComboBox.Items.Add(new Tools.ValueNameItem <int>(4, "Use 4-bit font anti-aliasing"));

            _graphicsAlphaComboBox.Items.Add(new Tools.ValueNameItem <int>(1, "Do not use graphics anti-aliasing"));
            _graphicsAlphaComboBox.Items.Add(new Tools.ValueNameItem <int>(2, "Use 2-bit graphics anti-aliasing"));
            _graphicsAlphaComboBox.Items.Add(new Tools.ValueNameItem <int>(4, "Use 4-bit graphics anti-aliasing"));

            // Now set the state of the controls

            CodecsPdfLoadOptions pdfLoadOptions = rasterCodecsInstance.Options.Pdf.Load;

            _useLibFontsCheckBox.Checked       = pdfLoadOptions.UseLibFonts;
            _displayDepthComboBox.SelectedItem = Tools.ValueNameItem <int> .SelectItem(pdfLoadOptions.DisplayDepth, _displayDepthComboBox.Items);

            _textAlphaComboBox.SelectedItem = Tools.ValueNameItem <int> .SelectItem(pdfLoadOptions.TextAlpha, _textAlphaComboBox.Items);

            _graphicsAlphaComboBox.SelectedItem = Tools.ValueNameItem <int> .SelectItem(pdfLoadOptions.GraphicsAlpha, _graphicsAlphaComboBox.Items);

            _disableCroppingCheckBox.Checked  = pdfLoadOptions.DisableCropping;
            _displayCieColorsCheckBox.Checked = pdfLoadOptions.DisableCieColors;
            _passwordTextBox.Text             = pdfLoadOptions.Password;
        }
Exemple #2
0
        /// <summary>
        /// Called by the owner to get the data
        /// </summary>
        public bool GetData(RasterCodecs rasterCodecsInstance)
        {
            CodecsPdfLoadOptions pdfLoadOptions = rasterCodecsInstance.Options.Pdf.Load;

            // Get the PDF load settings
            pdfLoadOptions.UseLibFonts = _useLibFontsCheckBox.Checked;
            if (_displayDepthComboBox.SelectedItem != null)
            {
                pdfLoadOptions.DisplayDepth = Tools.ValueNameItem <int> .GetSelectedItem(_displayDepthComboBox.SelectedItem);
            }

            if (_textAlphaComboBox.SelectedItem != null)
            {
                pdfLoadOptions.TextAlpha = Tools.ValueNameItem <int> .GetSelectedItem(_textAlphaComboBox.SelectedItem);
            }

            if (_graphicsAlphaComboBox.SelectedItem != null)
            {
                pdfLoadOptions.GraphicsAlpha = Tools.ValueNameItem <int> .GetSelectedItem(_graphicsAlphaComboBox.SelectedItem);
            }
            pdfLoadOptions.DisableCropping  = _disableCroppingCheckBox.Checked;
            pdfLoadOptions.DisableCieColors = _displayCieColorsCheckBox.Checked;
            pdfLoadOptions.Password         = _passwordTextBox.Text;

            return(true);
        }
Exemple #3
0
        private bool AddFile(string ofd)
        {
            if (File.Exists(ofd))
            {
                if (chkFiles.FindStringExact(ofd) == -1)
                {
                    using (RasterCodecs codecs = new RasterCodecs())
                    {
                        int pageCount = codecs.GetTotalPages(ofd);

                        if (requiredPageCount != pageCount)
                        {
                            return(false);
                        }
                    }

                    chkFiles.Items.Add(ofd, true);
                    chkFiles.TopIndex = chkFiles.Items.Count - 1;
                }

                // it's already in the list
                return(true);
            }

            return(false);
        }
Exemple #4
0
        public static void ExportPdfImage(string filename)
        {
            var outputFile = Path.Combine(Leadtools.Demo.Support.Path.GetOutputPath(), Path.GetFileNameWithoutExtension(filename) + "_Image.pdf");

            // Create instance of RasterCodecs object to load and save the file
            // https://www.leadtools.com/help/leadtools/v19/dh/co/leadtools.codecs~leadtools.codecs.rastercodecs.html
            using (var codecs = new RasterCodecs())
            {
                // We want to load all the pages of the file
                codecs.Options.Load.AllPages = true;

                // Load the image
                // https://www.leadtools.com/help/leadtools/v19/dh/l/leadtools~leadtools.rasterimage.html
                using (var image = codecs.Load(filename))
                {
                    if (image.BitsPerPixel != 1)
                    {
                        // Use the AutoBinarize Command to convert the image to 1bpp (black and white)
                        // https://www.leadtools.com/help/leadtools/v19/dh/po/leadtools.imageprocessing.core~leadtools.imageprocessing.core.autobinarizecommand.html
                        new AutoBinarizeCommand().Run(image);
                    }
                    // Save the image out as a 1BPP CCITT Group 4 compressed PDF
                    // https://www.leadtools.com/help/leadtools/v19/dh/co/leadtools.codecs~leadtools.codecs.rastercodecs~save.html
                    codecs.Save(image, outputFile, RasterImageFormat.RasPdfG4, 1);
                }
            }
        }
Exemple #5
0
        private void LoadOptionValues(RasterCodecs codec, string fileExtension)
        {
            if (".pdf".Equals(fileExtension, StringComparison.OrdinalIgnoreCase))
            {
                codec.Options.Pdf.InitialPath = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);//_scanDir;

                //_logFile.WriteToLog("PDF initial path = " + codec.Options.Pdf.InitialPath);
                codec.Options.RasterizeDocument.Load.XResolution = 204;
                codec.Options.RasterizeDocument.Load.YResolution = 196;
                //_logFile.WriteToLog("PDF options are loaded.");
            }
            else if (".rtf".Equals(fileExtension, StringComparison.OrdinalIgnoreCase))
            {
                codec.Options.RasterizeDocument.Load.TopMargin    = 0.5;
                codec.Options.RasterizeDocument.Load.BottomMargin = 0.5;
                codec.Options.RasterizeDocument.Load.LeftMargin   = 0.5;
                codec.Options.RasterizeDocument.Load.RightMargin  = 0.5;
                codec.Options.RasterizeDocument.Load.PageHeight   = 14;
                codec.Options.RasterizeDocument.Load.PageWidth    = 8.5;
                //_logFile.WriteToLog("RTF options are loaded");
            }
            else if (".txt".Equals(fileExtension, StringComparison.OrdinalIgnoreCase))
            {
                codec.Options.Txt.Load.Enabled = true;
                codec.Options.RasterizeDocument.Load.TopMargin    = 1.5;
                codec.Options.RasterizeDocument.Load.BottomMargin = 1.5;
                codec.Options.RasterizeDocument.Load.LeftMargin   = 1;
                codec.Options.RasterizeDocument.Load.RightMargin  = 1;
                codec.Options.Txt.Load.FontColor = new RasterColor(255, 0, 0);
                codec.Options.Txt.Load.FontSize  = 12;
                //_logFile.WriteToLog("TXT options are loaded");
            }
        }
Exemple #6
0
 static ExportExtensions()
 {
     _Codecs     = new RasterCodecs();
     _Anonymizer = new Anonymizer();
     _Anonymizer.ApplicationDescription  = "HTML5 Medical Viewer";
     _Anonymizer.BeforeTagAnonymization += new EventHandler <BeforeTagAnonymizationEventArgs>(_Anonymizer_BeforeTagAnonymization);
 }
        public async void AddProfileImage(ContactModel contactItem, RasterImage image, Stream imageStream)
        {
            string imageFileName = Path.GetFileNameWithoutExtension(contactItem.Picture).Replace("image_", "");
            string filePath      = Path.Combine(HomePage.PROFILE_PICS_DIR, $"profile_{imageFileName}.jpeg");

            if (imageStream != null)
            {
                await DependencyService.Get <IPictureSaver>().SaveImage(imageStream, filePath, PictureSaveResolution.Low, false);
            }
            else if (image != null)
            {
                LeadSize size = ImageSizeHelper.GetImageSize(image.Width, image.Height, PictureSaveResolution.Low);
                ResizeInterpolateCommand resizeInterpolateCommand = new ResizeInterpolateCommand(size.Width, size.Height, ResizeInterpolateCommandType.Resample);
                resizeInterpolateCommand.Run(image);

                using (var codecs = new RasterCodecs())
                {
                    codecs.Save(image, filePath, RasterImageFormat.Jpeg, 0);
                }
            }

            contactItem.ProfileImage = filePath;

            Device.BeginInvokeOnMainThread(() => profileImageView.Source = filePath);

            HomePage.Instance.SaveContactList();
        }
Exemple #8
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.

        }
Exemple #9
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);
        }
Exemple #10
0
        public override void PrepareToSave(RasterCodecs codecs, RasterImage image, int bpp, int qf)
        {
            // Set the format
            ImageFormat = RasterImageFormat.Gif;

            if (bpp != 0)
            {
                // User passed an explicit value, check if GIF supports it
                if (bpp <= 8)
                {
                    BitsPerPixel = bpp; // Yes
                }
                else
                {
                    BitsPerPixel = 8; // No, use default value
                }
            }
            else
            {
                // User did not pass a value, we need to figure it out from the image to produce an image that does not require more
                // size than the original keeping the quality the same.
                if (image.BitsPerPixel == 1)
                {
                    BitsPerPixel = 1;
                }
                else if (image.BitsPerPixel <= 4)
                {
                    BitsPerPixel = 4;
                }
                else
                {
                    BitsPerPixel = 8;
                }
            }
        }
Exemple #11
0
        protected override void Run()
        {
            int ticker = 0;
            int step   = (int)(100 / files.Length);

            RasterCodecs codecs = new RasterCodecs();

            for (int i = 0; i < files.Length; i++)
            {
                string file = files[i];
                Progress(ticker += step, $"Loading {file}...");

                try
                {
                    RasterImage image = codecs.Load(file);
                    image.CustomData.Add(FormName, System.IO.Path.GetFileName(file));

                    double scaleFactor = maxHeight / (double)image.ImageHeight;

                    int maxWidth = (int)(image.ImageWidth * scaleFactor);

                    RasterImage th = image.CreateThumbnail(maxWidth, maxHeight, image.BitsPerPixel, image.ViewPerspective, RasterSizeFlags.None);

                    th.CustomData.Add(OriginalImage, image);

                    OnImageLoaded(th);
                }
                catch (Exception ex)
                {
                    OnImageLoadError(file, ex.Message);
                }
            }

            base.Run();
        }
Exemple #12
0
        /// <summary>
        /// Called by the main form to set a new document into the viewer
        /// </summary>
        public void SetDocument(string documentFileName, int firstPageNumber, int lastPageNumber, RasterCodecs rasterCodecsInstance)
        {
            _documentFileName     = documentFileName;
            _rasterCodecsInstance = rasterCodecsInstance;

            // Create the pages thumbnails
            _imageList.Items.Clear();
            for (int pageNumber = firstPageNumber; pageNumber <= lastPageNumber; pageNumber++)
            {
                RasterImage thumbnailImage = _rasterCodecsInstance.Load(_documentFileName, 160, 160, 0, RasterSizeFlags.Resample, CodecsLoadByteOrder.BgrOrGray, pageNumber, pageNumber);
                if (thumbnailImage != null)
                {
                    int             viewPageNumber = pageNumber - firstPageNumber + 1;
                    ImageViewerItem item           = new ImageViewerItem();
                    item.Image = thumbnailImage;
                    item.Tag   = pageNumber;
                    item.Text  = "Page " + viewPageNumber.ToString();
                    _imageList.Items.Add(item);
                }
                _imageList.Items[0].IsSelected = true;
            }

            UpdateImageInfo();
            UpdatePageInfo();
            UpdateUIState();
        }
Exemple #13
0
        public override void PrepareToSave(RasterCodecs codecs, RasterImage image, int bpp, int qf)
        {
            // We will always use JPEG 422. This provides the best ratio between quality and performance and
            // supported by all major browsers
            ImageFormat = RasterImageFormat.Jpeg422;
            int qualityFactor;

            if (bpp == 12 || bpp == 16)
            {
                BitsPerPixel = bpp;
                // Gray scale image. QualityFactor 0 (lossless) is the only one supported. Note, none of the browsers currently
                // in the market supports lossless JPEGs
                qualityFactor = 0;
            }
            else
            {
                // Only other BPP supported is 8 or 24, so if it is not any of those, use 24
                if (bpp != 8 && bpp != 24)
                {
                    BitsPerPixel = 24;
                }

                // Set the quality factor
                qualityFactor = NormalizeQualityFactor(qf, 2, 255, 20);
            }

            // And set the quality factor
            codecs.Options.Jpeg.Save.QualityFactor = qualityFactor;
        }
Exemple #14
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);

            }

        }
Exemple #15
0
        protected override void OnLoad(EventArgs e)
        {
            if (!DesignMode)
            {
                using (Graphics g = CreateGraphics())
                {
                    Tools.Units.ScreenResolution = (int)g.DpiX;
                }

                // Setup the caption for this demo
                Messager.Caption = "C# Rasterize Document Demo";
                Text             = Messager.Caption;

                _rasterCodecsInstance = new RasterCodecs();

                // Setup and initialize the option controls
                foreach (TabPage tp in _optionsTabControl.TabPages)
                {
                    UserControls.IOptionsUserControl optionsUserControl = tp.Controls[0] as UserControls.IOptionsUserControl;
                    optionsUserControl.SetData(_rasterCodecsInstance);
                }

                _documentInfoControl.SetData(_imageInfo, _rasterCodecsInstance);
            }

            base.OnLoad(e);
        }
Exemple #16
0
        /// <summary>
        /// Called by the owner to get the data
        /// </summary>
        public bool GetData(RasterCodecs rasterCodecsInstance)
        {
            bool ret = true;

            string documentPath = _documentPathTextBox.Text.Trim();

            if (ret)
            {
                if (string.IsNullOrEmpty(documentPath))
                {
                    Messager.ShowWarning(this, "Enter the path of the document to load or click the browse button");
                    _documentPathTextBox.Focus();
                    ret = false;
                }
            }

            if (ret)
            {
                if (!File.Exists(documentPath))
                {
                    string message = string.Format(@"File:{0}{0}'{1}'{0}{0}Does not exist.", Environment.NewLine, documentPath);
                    Messager.ShowWarning(this, message);
                    _documentPathTextBox.Focus();
                    ret = false;
                }
            }

            _documentPath = documentPath;

            return(ret);
        }
Exemple #17
0
        private void FrmMain_Load(object sender, EventArgs e)
        {
            try
            {
                _codec = new RasterCodecs();
                _miPrinterDefaultSpecs.Visible = true;
                if (bSelectedPrinter == false)
                {
                    this.Close();
                }
                else
                {
                    _printDocument.PrintPage += new PrintPageEventHandler(_printDocument_PrintPage);
                }

                _miViewOutputFile.Checked = true;
                this.Text = "LEADTOOLS C# Printer Demo - Active printer is: " + _currentPrinterName;

                string newGuid = Guid.NewGuid().ToString("N");
                //Get the path to the shared documents
                _fontsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), newGuid);
                Directory.CreateDirectory(_fontsPath);
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "LEADTOOLS Printer Demo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            finally
            {
            }
        }
Exemple #18
0
        /// <summary>
        /// Called by the owner to get the data
        /// </summary>
        public bool GetData(RasterCodecs rasterCodecsInstance)
        {
            if (!GetFontSize())
            {
                return(false);
            }

            CodecsTxtLoadOptions txtLoadOptions = rasterCodecsInstance.Options.Txt.Load;

            // Get the TXT load settings

            txtLoadOptions.Enabled         = _enabledCheckBox.Checked;
            txtLoadOptions.UseSystemLocale = _useSystenLocaleCheckBox.Checked;

            txtLoadOptions.FaceName = _fontNameComboBox.Text;
            txtLoadOptions.FontSize = _fontSize;

            txtLoadOptions.Bold          = _fontBoldCheckBox.Checked;
            txtLoadOptions.Italic        = _fontItalicCheckBox.Checked;
            txtLoadOptions.Underline     = _fontUnderlineCheckBox.Checked;
            txtLoadOptions.Strikethrough = _fontStrikethroughCheckBox.Checked;

            txtLoadOptions.FontColor = Converters.FromGdiPlusColor(_fontColorPanel.BackColor);
            txtLoadOptions.BackColor = Converters.FromGdiPlusColor(_backColorPanel.BackColor);
            txtLoadOptions.Highlight = Converters.FromGdiPlusColor(_highlightColorPanel.BackColor);

            return(true);
        }
Exemple #19
0
        private bool SetDocumentLoadResultion(RasterCodecs codecs, CodecsImageInfo info, int firstPage, int lastPage)
        {
            if (!Is64)                            // No limit for x64
            {
                if (info.Document.IsDocumentFile) // if the file is a document file format
                {
                    if (firstPage < 1)
                    {
                        firstPage = 1;
                    }

                    if ((((lastPage == -1) && (info.TotalPages > maxDocPages)) || (lastPage - firstPage + 1 > maxDocPages)) && ((codecs.Options.RasterizeDocument.Load.XResolution > maxDocResolution) || (codecs.Options.RasterizeDocument.Load.YResolution > maxDocResolution)))
                    {
                        string promptMessage = string.Format("You are trying to load a document file which has more than {0} pages at {1} dpi.{2}{2}", maxDocPages, codecs.Options.RasterizeDocument.Load.XResolution, Environment.NewLine);
                        promptMessage = string.Format("{0}This can cause performance issues on machines with limited resources.{1}{1}", promptMessage, Environment.NewLine);
                        promptMessage = string.Format("{0}Click 'Yes' to reduce the resolution and continue loading or click 'No' to continue loading with the current resolution.", promptMessage);
                        DialogResult result = MessageBox.Show(promptMessage, "Warning", MessageBoxButtons.YesNoCancel);
                        switch (result)
                        {
                        case DialogResult.Yes:
                            codecs.Options.RasterizeDocument.Load.XResolution = 96;
                            codecs.Options.RasterizeDocument.Load.YResolution = 96;
                            break;

                        case DialogResult.No:
                            break;

                        case DialogResult.Cancel:
                            return(false);
                        }
                    }
                }
            }
            return(true);
        }
Exemple #20
0
        /// <summary>
        /// Called by the owner to initialize
        /// </summary>
        public void SetData(RasterCodecs rasterCodecsInstance)
        {
            _fontSizeComboBox.PreviewKeyDown += new PreviewKeyDownEventHandler(_textBox_PreviewKeyDown);
            _fontSizeComboBox.LostFocus      += new EventHandler(_fontSizeComboBox_LostFocus);

            FontFamily[] fontFamilies = FontFamily.Families;

            foreach (FontFamily ff in fontFamilies)
            {
                _fontNameComboBox.Items.Add(ff.Name);
            }

            // Set the state of the controls

            CodecsTxtLoadOptions txtLoadOptions = rasterCodecsInstance.Options.Txt.Load;

            _enabledCheckBox.Checked         = txtLoadOptions.Enabled;
            _useSystenLocaleCheckBox.Checked = txtLoadOptions.UseSystemLocale;

            _fontSize = txtLoadOptions.FontSize;
            _fontNameComboBox.Text             = txtLoadOptions.FaceName;
            _fontSizeComboBox.Text             = _fontSize.ToString();
            _fontBoldCheckBox.Checked          = txtLoadOptions.Bold;
            _fontItalicCheckBox.Checked        = txtLoadOptions.Italic;
            _fontUnderlineCheckBox.Checked     = txtLoadOptions.Underline;
            _fontStrikethroughCheckBox.Checked = txtLoadOptions.Strikethrough;

            _fontColorPanel.BackColor      = Converters.ToGdiPlusColor(txtLoadOptions.FontColor);
            _backColorPanel.BackColor      = Converters.ToGdiPlusColor(txtLoadOptions.BackColor);
            _highlightColorPanel.BackColor = Converters.ToGdiPlusColor(txtLoadOptions.Highlight);
        }
        private void Dispose(bool disposed)
        {
            if (autoEngine != null)
            {
                autoEngine.Dispose();
                autoEngine = null;
            }

            if (ocrEngines != null)
            {
                foreach (var ocrEngine in ocrEngines)
                {
                    ocrEngine.Shutdown();
                    ocrEngine.Dispose();
                }
            }

            if (rasterCodecs != null)
            {
                rasterCodecs.Dispose();
                rasterCodecs = null;
            }

            if (cleanUpOcrEngine != null)
            {
                cleanUpOcrEngine.Shutdown();
                cleanUpOcrEngine.Dispose();
                cleanUpOcrEngine = null;
            }

            ocrEngines = null;
        }
Exemple #22
0
        /*
         * Loads an image into the viewer
         */
        private void btnSelectImage_Click(object sender, EventArgs e)
        {
            try
            {
                using (RasterCodecs codecs = new RasterCodecs())
                {
                    ImageFileLoader loader = new ImageFileLoader();

                    loader.ShowLoadPagesDialog = true;

                    if (loader.Load(this, codecs, true) > 0)
                    {
                        rasterImageViewer.Image = loader.Image.Clone();
                        ((MainForm)Parent.Parent).btnNext.Enabled = true;
                    }

                    // Disable the next button if the user doesn't have an image and an item selected
                    ((MainForm)Parent.Parent).btnNext.Enabled = ((rasterImageViewer.Image != null) && (_globals.m_TreeResult.SelectedNode != null));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        private void loadImageButton_Click(object sender, EventArgs e)
        {
            string fileName = @"C:\Users\Public\Documents\LEADTOOLS Images\Barcode1.tif";

            // Or uncomment the following to load your own file
            //using(OpenFileDialog dlg = new OpenFileDialog())
            //{
            //   if(dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            //   {
            //      fileName = dlg.FileName;
            //   }
            //   else
            //   {
            //      return;
            //   }
            //}

            // Load the image
            using (RasterCodecs codecs = new RasterCodecs())
            {
                RasterImage newImage = codecs.Load(fileName, 0, CodecsLoadByteOrder.BgrOrGray, 1, 1);

                // Dispose of the image
                if (theImage != null)
                {
                    theImage.Dispose();
                }

                theImage      = newImage;
                imageFileName = fileName;
            }
            MessageBox.Show("Image loaded");
        }
        public void ConvertTifToPdf(string SourceFileName, string DestFileName)
        {
            RasterCodecs CodecsCommand = new RasterCodecs();
            RasterImage  LeadImage     = null;

            try
            {
                UnlockLeadToolsPDFSupport();
                //RasterCodecs.CodecsPath = codecsPath;
                //CodecsCommand.Options.Pdf.InitialPath = pdfInitialPath;
                CodecsCommand.Options.Pdf.Save.UseImageResolution     = true;
                CodecsCommand.Options.Tiff.Load.IgnoreViewPerspective = true;
                LeadImage = CodecsCommand.Load(SourceFileName);
                //LeadImage.ChangeCompression((LeadImage.IsSuperCompressed == true) ? RasterCompression.None : RasterCompression.Super);
                if (String.IsNullOrEmpty(DestFileName))
                {
                    DestFileName = System.IO.Path.Combine(System.IO.Path.GetTempPath().ToString(), Guid.NewGuid().ToString() + ".PDF");
                }

                CodecsCommand.Save(LeadImage, DestFileName, Leadtools.RasterImageFormat.RasPdf, 1, 1,
                                   LeadImage.PageCount, 1, Leadtools.Codecs.CodecsSavePageMode.Overwrite);
            }
            finally
            {
                if (LeadImage != null)
                {
                    LeadImage.Dispose();
                }
                if (CodecsCommand != null)
                {
                    CodecsCommand.Dispose();
                }
            }
        }
Exemple #25
0
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            // Clean up

            // Save the last setting
            Properties.Settings settings = new Properties.Settings();
            if (_ocrEngine != null)
            {
                settings.OcrEngineType = _ocrEngine.EngineType.ToString();
            }

            settings.Save();

            if (_ocrDocument != null)
            {
                _ocrDocument.Dispose();
                _ocrDocument = null;
            }

            // Dispose the OCR engine (this will call Shutdown as well)
            if (_ocrEngine != null)
            {
                _ocrEngine.Dispose();
                _ocrEngine = null;
            }

            if (_rasterCodecs != null)
            {
                _rasterCodecs.Dispose();
                _rasterCodecs = null;
            }

            base.OnFormClosed(e);
        }
        //fully qualified path & filename
        public LT_DPI_Converter(string srcFileName, string destFileName)
        {
            RasterCodecs codecs = new RasterCodecs();

            System.IO.File.Copy(srcFileName, destFileName, true);

                //Read Original Values
                RasterImage oldimage = codecs.Load(srcFileName);

                //Change values and save a new file name
                RasterImage newimage = codecs.Load(destFileName);
                int newResolution = 300; //BR says all files need to be 300 DPI. This should probably be an enum.

                // Load the source image from disk
                newimage.XResolution = newResolution;
                newimage.YResolution = newResolution;
                SizeCommand command = new SizeCommand();
                command.Width = oldimage.Width;
                command.Height = oldimage.Height;
                command.Flags = RasterSizeFlags.Resample;
                command.Run(newimage);
                //This changes the entire image and all pages. There is no need to pageinate.

                // Save the image back to disk
                codecs.Save(newimage, destFileName, RasterImageFormat.Tif, oldimage.BitsPerPixel);

            // Clean Up
                newimage.Dispose();
                oldimage.Dispose();
                codecs.Dispose();
        }
Exemple #27
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);

        }
Exemple #28
0
        public static void Startup()
        {
            //_logFile.WriteToLog("Applying Leadtools license...");
            string licenseFileName         = "";
            string licenseFileWithLocation = "";
            string developerKey            = "";

            try
            {
                string currDir = System.Reflection.Assembly.GetEntryAssembly().Location;
                currDir                 = Path.GetDirectoryName(currDir);
                licenseFileName         = Properties.Settings.Default.LeadtoolsLicenseFile;
                licenseFileWithLocation = currDir + @"\" + licenseFileName;
                developerKey            = Properties.Settings.Default.LeadtoolsDeveloperKey;

                //_logFile.WriteToLog("Applying license at: " + licenseFileWithLocation);
                //_logFile.WriteToLog("Applying key: " + developerKey);

                RasterSupport.SetLicense(licenseFileWithLocation, developerKey);
                //_logFile.WriteToLog("Applied Leadtools license.");

                codec = new RasterCodecs();
                //_logFile.WriteToLog("Lead tools Codec object is created");
            }
            catch (Exception e)
            {
                _logFile.WriteToLog("Problem applying Leadtools license:");
                _logFile.WriteToLog("LeadtoolsLicenseFile = " + licenseFileName);
                _logFile.WriteToLog("licenseFileWithLocation = " + licenseFileWithLocation);
                _logFile.WriteToLog("LeadtoolsLicenseFile = " + developerKey);
                _logFile.WriteToLog(e.StackTrace + "\nInner Exception: " + e.InnerException);
                throw e;
            }
        }
Exemple #29
0
        public static void MergeFiles(string mainFile, string appendFile, bool annotation)
        {
            if (MergeFilesByCopy(mainFile, appendFile))
            {
                return;
            }


            RasterCodecs codec = new RasterCodecs();
            RasterImage  image = null;

            RasterTagMetadata[] tagsData = null;  // stores the annotatin
            RasterImage         image2   = null;

            try
            {
                // load the image and annotation information for the
                // append file.
                image = codec.Load(appendFile);
                int pageCount = image.PageCount;
                if (annotation)
                {
                    tagsData = new RasterTagMetadata[pageCount];
                    for (int i = 0; i < pageCount; ++i)
                    {
                        tagsData[i] = codec.ReadTag(appendFile, i + 1, RasterTagMetadata.AnnotationTiff);
                    }
                }
                StatusForm statusForm = new StatusForm();
                statusForm.LoadFormData(appendFile, mainFile, pageCount);
                statusForm.Show();
                statusForm.Refresh();
                image2 = codec.Load(mainFile);
                int mainPageNumber = image2.PageCount;
                for (int i = 0; i < pageCount; ++i)
                {
                    codec.Save(image, mainFile, RasterImageFormat.CcittGroup4, 1, i + 1, i + 1, 1, CodecsSavePageMode.Append);
                    if (annotation)
                    {
                        if ((tagsData != null) && (tagsData[i] != null))
                        {
                            codec.WriteTag(mainFile, mainPageNumber + i + 1, tagsData[i]);
                        }
                    }
                    statusForm.ShowPageInfo(i);
                }
                statusForm.Close();
            }
            finally
            {
                if (image != null)
                {
                    image.Dispose();
                }
                if (image2 != null)
                {
                    image2.Dispose();
                }
            }
        }
        public async void AddBackImage(ContactModel contactItem, RasterImage backImage, Stream imageStream)
        {
            string imageFileName = Path.GetFileNameWithoutExtension(contactItem.Picture).Replace("image_", "");
            string backImagePath = Path.Combine(HomePage.APP_DIR, $"back_{imageFileName}.jpeg");

            if (imageStream != null)
            {
                await DependencyService.Get <IPictureSaver>().SaveImage(imageStream, backImagePath, PictureSaveResolution.Medium, false);
            }
            else if (backImage != null)
            {
                LeadSize size = ImageSizeHelper.GetImageSize(backImage.Width, backImage.Height, PictureSaveResolution.Medium);
                ResizeInterpolateCommand resizeInterpolateCommand = new ResizeInterpolateCommand(size.Width, size.Height, ResizeInterpolateCommandType.Resample);
                resizeInterpolateCommand.Run(backImage);

                using (var codecs = new RasterCodecs())
                {
                    codecs.Save(backImage, backImagePath, RasterImageFormat.Jpeg, 0);
                }
            }

            contactItem.BackImage = backImagePath;

            HomePage.Instance.SaveContactList();

            SetBackImage();
        }
Exemple #31
0
        /// <summary>
        /// Load Image callback. This is called as the image is decompressed
        /// </summary>
        void codecs_LoadImage(object sender, CodecsLoadImageEventArgs e)
        {
            IntPtr lineBuffer = e.Buffer.Data;

            for (int i = 0; i < e.Lines; i++)
            {
                if (bCancel)
                {
                    e.Cancel = true;
                    return;
                }

                try
                {
                    RasterCodecs _codecs = (RasterCodecs)sender;
                    _codecs.Compress(lineBuffer);
                    lineBuffer = new IntPtr(lineBuffer.ToInt64() + bytesPerLine);
                    UpdateStatus(e.Row, e.TotalPercent);
                }
                catch (Exception ex)
                {
                    Messager.ShowError(this, ex.Message);
                    e.Cancel = true;
                    return;
                }

                Application.DoEvents();
            }
        }
Exemple #32
0
        /// <summary>
        /// Initialize the application
        /// </summary>
        private void MainForm_Load(object sender, System.EventArgs e)
        {
            // setup our caption
            Messager.Caption = "LEADTOOLS for .NET C# JPEG 2000 Demo";
            Text             = Messager.Caption;

            // initialize the _viewer object
            _viewer           = new ImageViewer();
            _viewer.Dock      = DockStyle.Fill;
            _viewer.KeyPress += new KeyPressEventHandler(_viewer_KeyPress);
            _viewer.BackColor = Color.DarkGray;
            Controls.Add(_viewer);
            _viewer.BringToFront();
            _viewer.MouseDown += new MouseEventHandler(MyMouseDown);
            _viewer.MouseUp   += new MouseEventHandler(MyMouseUp);
            _viewer.MouseMove += new MouseEventHandler(MyMouseMove);

            // initialize the codecs object
            _codecs = new RasterCodecs();

            LoadImage(true);
            UpdateMyControls();

            _mousePath    = new System.Drawing.Drawing2D.GraphicsPath();
            _startDrawing = false;
            _myDrawPen    = new Pen(Color.Black, 2);
            _useROI       = false;
        }
Exemple #33
0
 public override void PrepareToSave(RasterCodecs codecs, RasterImage image, int bpp, int qf)
 {
     // Same as JPEG, just set the format to CMP
     base.PrepareToSave(codecs, image, bpp, qf);
     ImageFormat = RasterImageFormat.Cmp;
     codecs.Options.Jpeg.Save.CmpQualityFactorPredefined = CodecsCmpQualityFactorPredefined.Custom;
 }
        public static void Startup()
        {
            //_logFile.WriteToLog("Applying Leadtools license...");
            string licenseFileName = "";
            string licenseFileWithLocation = "";
            string developerKey = "";

            try
            { 
                string currDir = System.Reflection.Assembly.GetEntryAssembly().Location;
                currDir = Path.GetDirectoryName(currDir);
                licenseFileName = Properties.Settings.Default.LeadtoolsLicenseFile;
                licenseFileWithLocation = currDir + @"\" + licenseFileName;
                developerKey = Properties.Settings.Default.LeadtoolsDeveloperKey;

                //_logFile.WriteToLog("Applying license at: " + licenseFileWithLocation);
                //_logFile.WriteToLog("Applying key: " + developerKey);

                RasterSupport.SetLicense(licenseFileWithLocation, developerKey);
                //_logFile.WriteToLog("Applied Leadtools license.");

                codec = new RasterCodecs();
                //_logFile.WriteToLog("Lead tools Codec object is created");

            }
            catch (Exception e)
            {
                _logFile.WriteToLog("Problem applying Leadtools license:");
                _logFile.WriteToLog("LeadtoolsLicenseFile = " + licenseFileName);
                _logFile.WriteToLog("licenseFileWithLocation = " + licenseFileWithLocation);
                _logFile.WriteToLog("LeadtoolsLicenseFile = " + developerKey);
                _logFile.WriteToLog(e.StackTrace + "\nInner Exception: " + e.InnerException);
                throw e;
            }
        }
Exemple #35
0
        private void FastOptions_Load(object sender, System.EventArgs e)
        {
            _memoryFormatBPP   = new int[30];
            _memoryFormatMulti = new bool[30];
            _transferMode      = TwainTransferMode.Native;

            _rdTransferFile.Enabled   = false;
            _rdTransferMemory.Enabled = false;
            _rdTransferNative.Enabled = false;
            _txtFileName.Enabled      = false;
            _btnBrowse.Enabled        = false;
            _cmbFileFormats.Enabled   = false;
            _btnLEADFormats.Enabled   = false;
            _cbUseBufferSize.Enabled  = false;
            _txtBufferSize.Enabled    = false;

            if (MainForm.TwainAvailable)
            {
                CheckTransferMode(sender, e);
            }

            _btnOK.Enabled = false;

            _codecs = new RasterCodecs();
        }
Exemple #36
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);
 }
Exemple #37
0
 internal void Load(RasterCodecs codec)
 {
     if (fileName != null)
     {
         LoadFile(codec);
     }
     else if (stream != null)
     {
         LoadStream(codec);
     }
     
 }
Exemple #38
0
        public static bool ConvertDrawingImage(string strBasePath, string strSavePath)
        {
            try
            {
                RasterCodecs codecs = new RasterCodecs();
                RasterImage image = codecs.Load(strBasePath, 0, Leadtools.Codecs.CodecsLoadByteOrder.BgrOrGray, 1, 1);

                return SaveDrawingImage(image, strSavePath);
            }
            catch(Exception ex)
            {
                throw new Exception("WCF : Failed ConvertDrawingImage('" + ex.Message + "')");
            }
        }
        public static void GrayscaleTransformerVersion11(string srcFileName, string DestFileName)
        {
            RasterCodecs codecs = new RasterCodecs();
            UnlockLeadToolsDocumentSupport();

            IRasterImage image = null;
            int pageCount = 0;
            image = codecs.Load(srcFileName);

            pageCount = image.PageCount;
            var bitsPerPixel = 12;

            codecs.Save(image, DestFileName, RasterImageFormat.Tif, bitsPerPixel, 1, pageCount, 1, CodecsSavePageMode.Append);
            image.Dispose();
        }
Exemple #40
0
        private void ConvertFileFormat()
        {
            
            RasterCodecs codec = new RasterCodecs();
            //codec.Options.s
           // CodecsLoadOptions options = new CodecsLoadOptions();


            CodecsPdfLoadOptions options = codec.Options.Pdf.Load;


            //CodecsRtfLoadOptions options1 = codec.Options.Rtf.Load;
            //options1.

            RasterImage image = codec.Load(@"c:\leadtools\gas.pdf", 0, CodecsLoadByteOrder.RgbOrGray, 1, 1);
            

            codec.Save(image, @"c:\leadtools\gas.tif", RasterImageFormat.TifxFaxG4, 1, 1, image.PageCount, 1, CodecsSavePageMode.Overwrite);
            MessageBox.Show("Done");
        }
        public MainForm()
        {
            InitializeComponent();

             InitInteractiveModes();
             //
             // TODO: Add any constructor code after InitializeComponent call
             //
             Messager.Caption = "OCR Zones Rubberband Demo";

             _codecs = new RasterCodecs();

             // Use the new RasterizeDocumentOptions to default loading document files at 300 DPI
             _codecs.Options.RasterizeDocument.Load.XResolution = 300;
             _codecs.Options.RasterizeDocument.Load.YResolution = 300;

             InitializeViewer(_viewer);
             InitializeZoomComboBox();

             UpdateMyControls();
        }
        //fully qualified path & filename
        public LT11_DPI_Transformer(string srcFileName, string destFileName)
        {
            RasterCodecs codecs = new RasterCodecs();

            //Read Original Values
            IRasterImage image = codecs.Load(srcFileName);

            //Change values and save a new file name

            int newResolution = 300; //BR says all files need to be 300 DPI. This should probably be an enum, db table or config file.

            // Load the source image from disk
            image.XResolution = newResolution;
            image.YResolution = newResolution;
            SizeCommand command = new SizeCommand();
            command.Width = image.Width;
            command.Height = image.Height;
            command.Flags = RasterSizeFlags.Resample;
            command.Run(image);
            //This changes the entire image and all pages. There is no need to pageinate.

            codecs.Save(image, destFileName, RasterImageFormat.Tif, image.BitsPerPixel);
            image.Dispose();
        }
 public static void FillSection_Png( object sender, Leadtools.Printer.EmfEventArgs e )
 {
     ConsoleMethods.Info( "EMF Event: FillSection_Png" );
      const string format = "png";
      string path = Path.Combine(
     GetOutputRootPath(),
     format + @"\",
     GetRandomFileName( format ) );
      Directory.CreateDirectory( Path.GetDirectoryName( path ) );
      // Get the EMF in memory and save as PNG.
      Metafile metaFile = null;
      try
      {
     metaFile = new Metafile( e.Stream );
     IntPtr hEmf = metaFile.GetHenhmetafile();
     using ( RasterImage image = RasterImageConverter.FromEmf( hEmf, 0, 0, RasterColor.White ) )
     {
        using ( RasterRegion region = new RasterRegion( new LeadRect( 20, 30, 100, 200 ) ) )
        {
           image.SetRegion( null, region, RasterRegionCombineMode.Set );
           new FillCommand( RasterColor.FromKnownColor( RasterKnownColor.Black ) ).Run( image );
        }
        using ( RasterCodecs codecs = new RasterCodecs() )
        {
           codecs.Options.Png.Save.QualityFactor = 9;
           codecs.Save( image, path, RasterImageFormat.Png, 32 );
        }
     }
     ConsoleMethods.Success( "FillSection_Png: PNG saved. " );
     ConsoleMethods.Verbose( path );
      }
      catch ( Exception ex )
      {
     ConsoleMethods.Error( ex.Message, 4000 );
      }
 }
Exemple #44
0
        public PlikingServerMain()
        {
            InitializeComponent();
            
            Support.Unlock(false);
            _ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.Professional, false);
            _ocrEngine.Startup(null, null, null, null);
            RasterCodecs.Startup();
            _codecs = new RasterCodecs();
            LeadInitLanguageSupported();
            // Add some Language Plus Characters.
            StringBuilder sb = new StringBuilder();
            char[] langPlusCharacters = { (char)0x2446, (char)0x2447, (char)0x2448, (char)0x2449, (char)0x0 };
            sb.Append(langPlusCharacters);
            _ocrEngine.SettingManager.SetStringValue("Language.LanguagesPlusCharacters", sb.ToString());

            Thread th = new Thread(new ThreadStart(DoSplash));
            //th.ApartmentState = ApartmentState.STA;
            //th.IsBackground=true;
            th.Start();
            Thread.Sleep(2000);
            th.Abort();
            Thread.Sleep(1000);
        }
Exemple #45
0
 void SaveThumbnail(MedicalViewerCell _cell)
 {
     try
     {
         string _dcmFile = "";
         if (_cell.Tag != null) _dcmFile = _cell.Tag.ToString();
         int Detail_ID = _cell.TabIndex;
         if (_dcmFile.Trim() != "")
         {
             using (RasterCodecs _Codecs = new RasterCodecs())
             {
                 using (RasterImage _temp = _Codecs.Load(_dcmFile))
                 {
                     _Codecs.Save(_temp.CreateThumbnail(83, 100, _temp.BitsPerPixel, _temp.ViewPerspective, RasterSizeFlags.Bicubic), thumbnailFileName, RasterImageFormat.Png, 8);
                     UpdateThumbnailImgOnScheduled(thumbnailFileName,Detail_ID, 1);
                 }
             }
         }
     }
     catch
     {
     }
 }
Exemple #46
0
 public LeadWorker(IOcrEngine ocrEngine, RasterCodecs codecs)
 {
     _ocrEngine = ocrEngine;
     _codecs = codecs;
 }
        private void LoadOptionValues(RasterCodecs codec, string fileExtension )
        {

            if (".pdf".Equals(fileExtension,StringComparison.OrdinalIgnoreCase))
            {
                codec.Options.Pdf.InitialPath = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);//_scanDir;
                
                //_logFile.WriteToLog("PDF initial path = " + codec.Options.Pdf.InitialPath);
                codec.Options.RasterizeDocument.Load.XResolution = 204;
                codec.Options.RasterizeDocument.Load.YResolution = 196;
                //_logFile.WriteToLog("PDF options are loaded.");
            }
            else if (".rtf".Equals(fileExtension, StringComparison.OrdinalIgnoreCase))
            {
                codec.Options.RasterizeDocument.Load.TopMargin = 0.5;
                codec.Options.RasterizeDocument.Load.BottomMargin = 0.5;
                codec.Options.RasterizeDocument.Load.LeftMargin = 0.5;
                codec.Options.RasterizeDocument.Load.RightMargin = 0.5;
                codec.Options.RasterizeDocument.Load.PageHeight = 14;
                codec.Options.RasterizeDocument.Load.PageWidth = 8.5;
                //_logFile.WriteToLog("RTF options are loaded");
            }
            else if (".txt".Equals(fileExtension,StringComparison.OrdinalIgnoreCase))
            {

                codec.Options.Txt.Load.Enabled = true;
                codec.Options.RasterizeDocument.Load.TopMargin = 1.5;
                codec.Options.RasterizeDocument.Load.BottomMargin = 1.5;
                codec.Options.RasterizeDocument.Load.LeftMargin = 1;
                codec.Options.RasterizeDocument.Load.RightMargin = 1;
                codec.Options.Txt.Load.FontColor = new RasterColor(255, 0, 0);
                codec.Options.Txt.Load.FontSize = 12;
                //_logFile.WriteToLog("TXT options are loaded");
            }
        }
Exemple #48
0
        private static void DoExtraction(string srcFileName, string destFileName, int[] pageNumList, bool annotation)
        {
            RasterCodecs codec = new RasterCodecs();
            RasterImage image = null;
            RasterTagMetadata[] tagsData = null;

            try
            {
                image = codec.Load(srcFileName);
                int pageCount = image.PageCount;
                if (annotation)
                {
                    tagsData = new RasterTagMetadata[pageCount];
                    for (int i = 0; i < pageCount; ++i)
                    {
                        tagsData[i] = codec.ReadTag(srcFileName, i + 1, RasterTagMetadata.AnnotationTiff);
                    }
                }
                int listCount = pageNumList.Length;
                if (File.Exists(destFileName))
                {
                    File.Delete(destFileName);
                }
                StatusForm statusForm = new StatusForm();
                statusForm.LoadFormData(srcFileName, destFileName, listCount);
                statusForm.Show();
                statusForm.Refresh();
                for (int i = 0; i < listCount; ++i)
                {
                    codec.Save(image, destFileName, RasterImageFormat.CcittGroup4, 1, pageNumList[i], pageNumList[i], i, CodecsSavePageMode.Append);
                    if (annotation)
                    {
                        if ((tagsData != null) && (tagsData[pageNumList[i] - 1] != null))
                        {
                            codec.WriteTag(destFileName, i + 1, tagsData[pageNumList[i]-1]);
                        }
                    }
                    statusForm.ShowPageInfo(pageNumList[i]);
                }

                if (image.PageCount > listCount)
                {
                    int deleteCount = 0;
                    for (int i = 1; i <= pageCount; ++i)
                    {
                        if (PageNumberFound(i, pageNumList))
                        {
                            image.RemovePageAt(i+deleteCount);
                            deleteCount--;
                        }
                    }
                    codec.Save(image, srcFileName, RasterImageFormat.CcittGroup4, 1, 1, image.PageCount, 1, CodecsSavePageMode.Overwrite);
                    if (annotation)
                    {
                        int newPageIndex = 0;
                        for (int i = 0; i < pageCount; ++i)
                        {
                            if (!PageNumberFound(i+1, pageNumList) && (tagsData != null) && (tagsData[i] != null))
                            {
                               codec.WriteTag(srcFileName, ++newPageIndex, tagsData[i]);
                            }
                        }
                    }
                    
                }
                else
                {
                    File.Delete(srcFileName);
                }
                statusForm.Close();

            }
            finally
            {
                if (image != null) {
                    image.Dispose();
                }
            }

        }
Exemple #49
0
        public static void MergeFiles(string mainFile, string appendFile, bool annotation)
        {


            if (MergeFilesByCopy(mainFile, appendFile))
            {
                return;
            }
            

            RasterCodecs codec = new RasterCodecs();
            RasterImage image = null;
            RasterTagMetadata[] tagsData = null;  // stores the annotatin
            RasterImage image2 = null;
            try
            {
                // load the image and annotation information for the 
                // append file.
                image = codec.Load(appendFile);
                int pageCount = image.PageCount;
                if (annotation)
                {
                    tagsData = new RasterTagMetadata[pageCount];
                    for (int i = 0; i < pageCount; ++i)
                    {
                        tagsData[i] = codec.ReadTag(appendFile, i + 1, RasterTagMetadata.AnnotationTiff);
                    }
                }
                StatusForm statusForm = new StatusForm();
                statusForm.LoadFormData(appendFile, mainFile, pageCount);
                statusForm.Show();
                statusForm.Refresh();
                image2 = codec.Load(mainFile);
                int mainPageNumber = image2.PageCount;
                for (int i = 0; i < pageCount; ++i)
                {
                    codec.Save(image, mainFile, RasterImageFormat.CcittGroup4, 1,  i + 1, i + 1, 1, CodecsSavePageMode.Append);
                    if (annotation)
                    {
                        if ((tagsData != null) && (tagsData[i] != null))
                        {
                            codec.WriteTag(mainFile, mainPageNumber + i + 1, tagsData[i]);
                        }
                    }
                    statusForm.ShowPageInfo(i);
                }
                statusForm.Close();

            }
            finally
            {
                if (image != null)
                {
                    image.Dispose();
                }
                if (image2 != null)
                {
                    image2.Dispose();
                }
            }


        }
Exemple #50
0
        void RealizeAnnotationV2()
        {
            try
            {
                // Create and set up the container
                AnnContainer container = new AnnContainer();
                IntPtr hdc = RasterImagePainter.CreateLeadDC(_CurrCell.Image);
                container.Bounds = new AnnRectangle(0, 0, _CurrCell.Image.ImageWidth, _CurrCell.Image.ImageHeight);
                container.UnitConverter = new AnnUnitConverter(_CurrCell.Image.XResolution, _CurrCell.Image.YResolution);
                container.Draw(_CurrCell.Image);
                using (RasterCodecs _codecs = new RasterCodecs())
                {
                    _codecs.Save(_CurrCell.Image, _CurrCell.Image.Tags.ToString(), RasterImageFormat.DicomGray, _CurrCell.Image.BitsPerPixel);
                }
               


            }
            catch
            {
            }
        }
Exemple #51
0
 private void SaveToFile(string fileName)
 {
     RasterCodecs codec = new RasterCodecs();
     if (File.Exists(fileName)) {
         File.Delete(fileName);
     }
     for (int i=0;i<destImageList.Items.Count;++i){
         codec.Save(destImageList.Items[i].Image, fileName, RasterImageFormat.Tif, 0, i + 1, i + 1, i + 1, CodecsSavePageMode.Append);
     }
 }
Exemple #52
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);
        }
Exemple #53
0
        public void TestOpen()
        {
            string fileName = @"C:\Images\Chest.dcm";
            if (File.Exists(fileName))
            {
                try
                {

                    using (RasterCodecs _codecs = new RasterCodecs())
                    {
                        using (RasterImage _image = _codecs.Load(fileName))
                        {
                            MedicalViewerMultiCell cell = new MedicalViewerMultiCell();
                            cell.FitImageToCell = true;
                            cell.Columns = 1;
                            cell.Rows = 1;
                            DicomDataSet ds = new DicomDataSet();
                            try
                            {

                                ds.Load(fileName, DicomDataSetLoadFlags.LoadAndClose);
                            }
                            catch (Exception ex) { ds = null; }
                            if (ds != null)
                            {
                                // dosomething here
                            }
                            _DicomMedicalViewer._medicalViewer.Cells.Add(cell);
                            cell.Image = _image.CloneAll();
                            cell.Selected = true;
                            _DicomMedicalViewer._medicalViewer.Invalidate();
                        }
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }
Exemple #54
0
         public void OpenDicom( ref bool IsCroping, ref int _Idx, string fileName, bool IsOnlyImg, bool CanCreatePicBox)
         {
             //Stopwatch _sw = new Stopwatch();
             try
             {
                 _DicomMedicalViewer._medicalViewer.BeginUpdate();
                 pnlScheduled.Enabled = false;
                 //_sw.Start();
                
                 #region Chế độ Demo
                 if (_AppMode == AppType.AppEnum.AppMode.Demo && !File.Exists(fileName))
                 {
                     ScheduledControl _selected = GetSelectedScheduled();
                     bool _isSelected = true;
                     string RAWFilePath = "";
                     //Tạo các thư mục theo cấp ngày\Bệnh nhân(Mã bệnh nhân _ Tên Bệnh nhân _ Tuổi)
                     if (!Directory.Exists(txtImgDir.Text + @"\" + SubDirLv1())) Directory.CreateDirectory(txtImgDir.Text + @"\" + SubDirLv1());
                     if (!Directory.Exists(txtImgDir.Text + @"\" + SubDirLv1() + @"\" + SubDirLv2_Patient())) Directory.CreateDirectory(txtImgDir.Text + @"\" + SubDirLv1() + @"\" + SubDirLv2_Patient());
                     //Kiểm tra nếu chưa chọn thủ tục nào thì cần lưu ảnh thành tên file theo định dạng
                     //YYYY_MM_DD_HH_mm_ss
                     if (_selected == null || RAWFileNameWillbeCreated == "NONE_SELECTED")
                     {
                         _isSelected = false;
                         RAWFileNameWillbeCreated = "NONE_SELECTED_" + Utility.GetYYYYMMDDHHMMSS(DateTime.Now);
                         if (!Directory.Exists(txtImgDir.Text + @"\" + SubDirLv1() + @"\" + SubDirLv2_Patient() + @"\NONE_SELECTED")) Directory.CreateDirectory(txtImgDir.Text + @"\" + SubDirLv1() + @"\" + SubDirLv2_Patient() + @"\NONE_SELECTED");
                         RAWFilePath = txtImgDir.Text + @"\" + SubDirLv1() + @"\" + SubDirLv2_Patient() + @"\NONE_SELECTED\" + RAWFileNameWillbeCreated + ".RAW";
                     }
                     else
                         RAWFilePath = txtImgDir.Text + @"\" + SubDirLv1() + @"\" + SubDirLv2_Patient() + @"\" + RAWFileNameWillbeCreated + ".RAW";//RAWFileNameWillbeCreated=REGNUM+_Detail_ID+_ACode+_Pcode tại phần click của Scheduled
                     fileName = Application.StartupPath + @"\DemoImg\" + m_strCurrACode + "-" + m_strCurrPCode + ".DCM";
                     string destFile = RAWFilePath.ToUpper().Replace(".RAW", ".DCM");
                     try2MoveFileInDemoMode(fileName, destFile);
                     fileName = destFile;
                     //Tự động cập nhật kết quả đã có hình ảnh
                     AutoUpdateResultAfterCapturingPictureFromModality();
                     AutoUpdatePatientInforInDcmFile_DemoMode(Path.GetDirectoryName(fileName), fileName, txtID2.Text, txtName2.Text, txtAge.Text, Sex,_selected.StudyInstanceUID, _selected.SeriesInstanceUID, _selected.SOPInstanceUID);
                 }
                 #endregion

                 isLoadding = true;
                 //stopToolStripMenuItem1_Click(mnuStop, new EventArgs());
                 TempCrop = IsCroping;
                 int _ww = 0;
                 int _wc = 0;
                 this.Text = MultiLanguage.GetText(globalVariables.DisplayLanguage, "VietBaIT JCS - DROC", "VietBaIT JSC-DROC");
                 if (!IsCroping) FilePath = fileName;
                 bool IsRawFile = false;
                 _images = 1;
                
                     try
                     {
                         #region Xử lý lại ảnh dcm từ ảnh gốc(Raw file)
                         try
                         {
                             if (IsGenDcmFromRaw)
                             {
                                 IsGenDcmFromRaw = false;
                                 string tempf_raw = fileName.ToUpper().Replace(".DCM", ".RAW");

                                 //Kiểm tra xem có ảnh Raw không
                                 if (File.Exists(tempf_raw))
                                 {
                                     //xóa file Dcm đang có
                                     string tempf_dcm = fileName.ToUpper().Replace(".RAW", ".DCM");
                                     try
                                     {
                                         File.Delete(tempf_dcm);
                                     }
                                     catch
                                     {
                                     }
                                     //Gán lại giá trị cho fileName để bước kế tiếp load lại raw file
                                     fileName = tempf_raw;
                                 }

                             }
                         }
                         catch(Exception ex0)
                         {
                             AppLogger.LogAction.LogActions("==>OpenDicom.if (IsGenDcmFromRaw)().Exception occurred at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + "." + ex0.ToString());
                         }
                         try
                         {
                             if (Path.GetExtension(fileName).ToUpper().Contains("RAW"))
                             {
                                 if (IsUsingDicomConverter || lblAutoDcmConverter.IsChecked)//Tự động convert thành file Dicom
                                 {
                                     ConvertRaw2DicomFileReprocess(fileName);
                                     AutoUpdateResultAfterCapturingPictureFromModality();
                                     fileName = fileName.ToLower().Replace(".raw", ".dcm");
                                     IsUsingDicomConverter = true;
                                     v_blnHasConvertRawin2DicomFile = true;
                                     //Thực hiện thuật toán xử lý ảnh ở ngay sau bước load ảnh Dicom

                                 }
                                 else
                                 {
                                     new frm_LargeMsgBoxOK(MultiLanguage.GetText(globalVariables.DisplayLanguage, "Thông báo", "Warning"), MultiLanguage.GetText(globalVariables.DisplayLanguage, "Cần vào tab Cấu hình đánh dấu vào mục tự động Convert thành file Dicom", "go to Configuration Tab and check Auto Convert to Dicom File"), MultiLanguage.GetText(globalVariables.DisplayLanguage, "Đã hiểu", "OK"), MultiLanguage.GetText(globalVariables.DisplayLanguage, "Không hiểu", "Cancel")).ShowDialog();
                                 }
                             }
                         }
                         catch (Exception ex01)
                         {
                             AppLogger.LogAction.LogActions("==>OpenDicom.ReGenDcmFromRAWFile().Exception occurred at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + "." + ex01.ToString());
                         }
                         #endregion
                         
                         if (File.Exists(fileName))
                         {
                             AppLogger.LogAction.AddLog2List(lstFPD560,DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + fileName + " exists");
                             FreeMemoryCapturedByMedicalviewerCell();
                             using (RasterCodecs _codecs = new RasterCodecs())
                             {
                                 //using (CounterDialog counter = new CounterDialog(this, _codecs))
                                 //{
                                 //    counter.Show(this);
                                 //    counter.Update();
                                 //if (chkLoadIn2Memory.IsChecked==false ) _codecs.Options.Load.DiskMemory = true;

                                 if (_codecs.Options.Load.DiskMemory) SetText(lblUsingMemo, "MEM");
                                 else SetText(lblUsingMemo, "NOTMEM");
                                 using (RasterImage _image = _codecs.Load(fileName))
                                 {

                                     cmdCreateDcmfromRaw.Enabled = true;
                                     //try2FreeImage(orginalImg);
                                    _DicomMedicalViewer.try2FreeImage(ref orginalImg);
                                     // try2FreeOriginalImage();
                                     if (_CurrCell != null)
                                     {
                                         RasterImage img = _CurrCell.Image;
                                         _DicomMedicalViewer.try2FreeImage(ref img);
                                     }
                                     orginalImg = _image.CloneAll();
                                     //Xóa các cell sau khi đã giải phóng bộ nhớ
                                     _DicomMedicalViewer._medicalViewer.Cells.Clear();
                                     //Tạo cell mới
                                     MedicalViewerMultiCell cell = new MedicalViewerMultiCell();
                                     cell.BeginUpdate();
                                     cell.FitImageToCell = true;
                                     cell.Columns = 1;
                                     cell.Rows = 1;
                                     _DicomMedicalViewer.InitializeCell(cell);
                                     _DicomMedicalViewer.CopyPropertiesFromGlobalCell(cell);
                                     _Idx = 0;
                                     if (IsOnlyImg) return;
                                     CurrCellFileName = fileName;
                                     //cell.SetTag(4, MedicalViewerTagAlignment.TopLeft, MedicalViewerTagType.Frame);
                                     cell.SetTag(6, MedicalViewerTagAlignment.TopLeft, MedicalViewerTagType.Scale);
                                     cell.SetTag(2, MedicalViewerTagAlignment.BottomLeft, MedicalViewerTagType.WindowLevelData);
                                     //cell.SetTag(1, MedicalViewerTagAlignment.BottomLeft, MedicalViewerTagType.FieldOfView);
                                     cell.SetTag(0, MedicalViewerTagAlignment.BottomLeft, MedicalViewerTagType.RulerUnit);
                                     DicomDataSet ds = new DicomDataSet();

                                     try
                                     {
                                         ds.Load(fileName, DicomDataSetLoadFlags.LoadAndClose);
                                         CurrentDicomDS = ds;
                                     }
                                     catch (Exception ex) { ds = null; }
                                     //DicomDS.Add(fileName, ds);
                                     if (ds != null)
                                     {

                                         if (IsRawFile)
                                             AutpSetDefaultTagForImgInfor(fileName, ds);
                                         _ww = Convert.ToInt32(GetStringValue(ds, DicomTag.WindowWidth));
                                         _wc = Convert.ToInt32(GetStringValue(ds, DicomTag.WindowCenter));
                                         string ID_Name = GetStringValue(ds, Leadtools.Dicom.DicomTag.PatientID) + " " + GetStringValue(ds, Leadtools.Dicom.DicomTag.PatientName);
                                         string Birthday_Sex_Age = "";
                                         string BD = GetStringValue(ds, Leadtools.Dicom.DicomTag.PatientBirthDate).Trim();
                                         string BT = GetStringValue(ds, Leadtools.Dicom.DicomTag.PatientBirthTime).Trim();
                                         string Sex = TranslateSex(GetStringValue(ds, Leadtools.Dicom.DicomTag.PatientSex).Trim());
                                         string Age = GetStringValue(ds, Leadtools.Dicom.DicomTag.PatientAge).Trim();
                                         ID_Name_Age_Sex = ID_Name + " " + Age + " " + Sex;
                                         if (BD != "") Birthday_Sex_Age += BD;
                                         //if (BT != "") Birthday_Sex_Age += BD;
                                         if (Sex != "") Birthday_Sex_Age += " [" + Sex + "] ";
                                         if (Age != "") Birthday_Sex_Age += Age + " T";
                                         //Mã+Tên BN
                                         cell.SetTag(0, MedicalViewerTagAlignment.TopLeft, MedicalViewerTagType.UserData, ID_Name);
                                         //Ngày sinh-Giới tính-Tuổi
                                         cell.SetTag(1, MedicalViewerTagAlignment.TopLeft, MedicalViewerTagType.UserData, Birthday_Sex_Age);
                                         //Các thông tin khác

                                         cell.SetTag(0, MedicalViewerTagAlignment.TopRight, MedicalViewerTagType.UserData, HospitalName);
                                         cell.SetTag(1, MedicalViewerTagAlignment.TopRight, MedicalViewerTagType.UserData, DepartmentName);
                                         cell.SetTag(2, MedicalViewerTagAlignment.TopRight, MedicalViewerTagType.UserData, DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                                     }
                                     else
                                     {
                                         //Mã+Tên BN
                                         cell.SetTag(0, MedicalViewerTagAlignment.TopLeft, MedicalViewerTagType.UserData, "");
                                         //Ngày sinh-Giới tính-Tuổi
                                         cell.SetTag(1, MedicalViewerTagAlignment.TopLeft, MedicalViewerTagType.UserData, "");
                                         //Các thông tin khác

                                         cell.SetTag(0, MedicalViewerTagAlignment.TopRight, MedicalViewerTagType.UserData, "");
                                         cell.SetTag(1, MedicalViewerTagAlignment.TopRight, MedicalViewerTagType.UserData, "");
                                         cell.SetTag(2, MedicalViewerTagAlignment.TopRight, MedicalViewerTagType.UserData, "");
                                     }

                                     //Load Annotation
                                     string Anfn = GetAnnPath(fileName);
                                     if (System.IO.File.Exists(Anfn))
                                     {
                                         LoadAnnotation(cell, Anfn, true);
                                     }

                                    _DicomMedicalViewer.ApplyToCell(cell);
                                     cell.ShowTags = lblDisplayTag.IsChecked;
                                     cell.DisplayRulers = (MedicalViewerRulers)cboRuler.SelectedIndex;
                                     AddNewMecicalViewerCell(cell);
                                     int CellCount = _DicomMedicalViewer._medicalViewer.Cells.Count;
                                     _Idx = CellCount - 1;
                                     //Dùng CloneAll() để giải phóng _image

                                     cell.Tag = fileName;
                                     if (GetSelectedScheduled() != null)
                                         cell.TabIndex = GetSelectedScheduled().DETAIL_ID;
                                     else
                                         cell.TabIndex = m_intCurrentDetail_ID <= 0 ? 0 : m_intCurrentDetail_ID;
                                     //v_blnHasConvertRawin2DicomFile=true xảy ra ở 2 sự kiện
                                     //1. Nhận ảnh từ FPD và có tự động chuyển thành file Dicom
                                     //2. Nhận ảnh từ FPD và để dưới dạng file RAW, sau đó tại hàm OpenDicom() nếu chưa có ảnh Dcm sẽ tự động Convert file RAW thành DCM
                                     if (v_blnHasConvertRawin2DicomFile && lblDisplayRaw.ImageIndex != 0)
                                     {
                                             using (Cursor _Cursor = Cursors.WaitCursor)
                                             {
                                                 AppLogger.LogAction.ShowEventStatus(lblFPDStatus,MultiLanguage.GetText(globalVariables.DisplayLanguage, "Đang xử lý ảnh...", "image processing..."));
                                                 AppLogger.LogAction.AddLog2List(lstFPD560,DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + MultiLanguage.GetText(globalVariables.DisplayLanguage, "Đang xử lý ảnh...", "image processing..."));
                                                 _DicomMedicalViewer.ApplyIEConfig(_currDRIEData, _image, lblGridMode.IsChecked, lblAppliedMed.IsChecked);
                                                 AutoApplyWW_WC(_image);
                                                 AppLogger.LogAction.AddLog2List(lstFPD560,DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + MultiLanguage.GetText(globalVariables.DisplayLanguage, "Đã xử lý xong...", "image processed..."));
                                                 AppLogger.LogAction.ShowEventStatus(lblFPDStatus,MultiLanguage.GetText(globalVariables.DisplayLanguage, "Đã xử lý xong...", "image processed..."));

                                                 if ( ((_FPDMode != AppType.AppEnum.FPDMode.Other && chkAutoVFlip1.IsChecked) || (_FPDMode == AppType.AppEnum.FPDMode.Other && ((FPDSeq == 1 && chkAutoVFlip1.IsChecked) || (FPDSeq == 2 && chkAutoVFlip2.IsChecked)))))
                                                 {
                                                     _DicomMedicalViewer.ApplyFilter(_image, new FlipCommand(true));
                                                 }
                                                 if (((_FPDMode != AppType.AppEnum.FPDMode.Other && chkAutoHFlip1.IsChecked) || (_FPDMode == AppType.AppEnum.FPDMode.Other && ((FPDSeq == 1 && chkAutoHFlip1.IsChecked) || (FPDSeq == 2 && chkAutoHFlip2.IsChecked)))))
                                                 {
                                                     _DicomMedicalViewer.ApplyFilter(_image, new FlipCommand(false));
                                                 }
                                                 if (AUTO_FLIPV == 1)
                                                 {
                                                     _DicomMedicalViewer.ApplyFilter(_image, new FlipCommand(true));
                                                 }
                                                 if (AUTO_FLIPH == 1)
                                                 {
                                                     _DicomMedicalViewer.ApplyFilter(_image, new FlipCommand(false));
                                                 }
                                                 AutoDetectRowsAndCols(cell, _image.PageCount);
                                                 cell.Image = _image.CloneAll();
                                                 if (!_DicomMedicalViewer.IsValidCell()) return;
                                                 _DicomMedicalViewer._medicalViewer.Cells.SelectAll(false);
                                                 _DicomMedicalViewer._medicalViewer.VisibleRow = _Idx;
                                                 cell.Selected = true;
                                                 _DicomMedicalViewer._medicalViewer.Invalidate();
                                                 if (AllowAppliedWL)
                                                 {
                                                     _DicomMedicalViewer.SetWindowLevel(cell, WW,WC);
                                                     
                                                 }
                                                 AllowAppliedWL = true;
                                             }

                                             _ww = WW;
                                             _wc = WC;
                                         //Thử tạo thông tin Annotation
                                         //CreateDefaultAnnotationOnImage(_DicomMedicalViewer._medicalViewer, Color.White, Color.Black, HospitalName, DepartmentName, ID_Name_Age_Sex, DateTime.Now.ToString("dd/MM/yyyy"));
                                         SaveImg();
                                         v_blnHasConvertRawin2DicomFile = false;
                                         //Tự động chuyển sang Tab xử lý ảnh
                                         tabCtrlAcq.SelectedTab = tabPageImgTools;
                                         //PlayBeep(5);
                                     }
                                     else
                                     {
                                         AutoDetectRowsAndCols(cell, _image.PageCount);
                                         cell.Image = _image.CloneAll();
                                         //cell.Bounds = cell.GetDisplayedClippedImageRectangle();
                                         if (!_DicomMedicalViewer.IsValidCell()) return;
                                         _DicomMedicalViewer._medicalViewer.Cells.SelectAll(false);
                                         _DicomMedicalViewer._medicalViewer.VisibleRow = _Idx;
                                         cell.Selected = true;
                                         _DicomMedicalViewer._medicalViewer.Invalidate();
                                         if (_AppMode == AppType.AppEnum.AppMode.Demo && FirstExposure)
                                         {
                                             SaveImg();
                                         }
                                     }
                                     //Áp dụng windowLeveling khi thực hiện lưu ảnh.
                                     //AutoApplyWW_WC();
                                     if (_ww != 0)
                                     {
                                         _DicomMedicalViewer.SetWindowLevel(cell,_ww,_wc);

                                         _DicomMedicalViewer._medicalViewer.Invalidate();
                                     }
                                     cell.EndUpdate();
                                     _DicomMedicalViewer._medicalViewer.Invalidate();
                                 }
                                 // }
                             }
                             _DicomMedicalViewer._medicalViewer.EndUpdate();
                             AppLogger.LogAction.ShowEventStatus(lblFPDStatus,MultiLanguage.GetText(globalVariables.DisplayLanguage, "Mời bạn tiếp tục xử lý", "Image Result"));
                         }
                         else
                         {
                             mdlStatic.isDisplayImg = false;
                             if (_AppMode == AppType.AppEnum.AppMode.License || (_AppMode == AppType.AppEnum.AppMode.Demo && _ViewState == AppType.AppEnum.ViewState.Capture))
                                 MessageBox.Show("Không tồn tại file ảnh sau:\n" + fileName);
                         }
                     }
                     catch (Exception ex)
                     {

                         AppLogger.LogAction.LogActions("==>OpenDicom.SecondsException().Exception occurred at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + "." + ex.ToString());
                         Utility.ShowMsg("2225 " + ex.ToString() + "\n" + fileName);
                         GC.Collect();
                         isLoadding = false;
                        
                         DeleteCurrentImg(_DicomMedicalViewer._medicalViewer, _DicomMedicalViewer._medicalViewerCellIndex);

                     }
                     finally
                     {
                         isLoadding = false;

                     }
                
                 isLoadding = false;
             }
             catch (Exception ex1)
             {
                 AppLogger.LogAction.LogActions("==>OpenDicom.FirstException().Exception occurred at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + "." + ex1.ToString());
                 AppLogger.LogAction.AddLog2List(lstFPD560,"0002: " + ex1.Message);
             }
             finally
             {
                 _DicomMedicalViewer._medicalViewer.BeginUpdate();
                 pnlScheduled.Enabled = true;
                //_sw.Stop();
                 //AppLogger.LogAction.ShowEventStatus(lblFPDStatus,((decimal)_sw.ElapsedMilliseconds / 1000).ToString());
                 IsUsingDicomConverter = false;
                 lblMemory.Text = getAvailableRAM();
                 //Kiểm tra nếu đang chế độ Crop mà lại chọn mục xem lại ảnh gốc thì cần khôi phục lại chế độ đó
                 if (_DicomMedicalViewer._IsCropping && IsLoadOriginalImage)
                 {
                     cmdAcqCrop_Click(cmdAcqCrop,new EventArgs());//Trạng thái ban đầu
                     cmdAcqCrop_Click(cmdAcqCrop, new EventArgs());//Trạng thái Crop
                 } 
             }
         }
Exemple #55
0
        void DROC_RibbonKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Alt && e.Shift && e.KeyCode == Keys.K)
                {
                    Autosave4Toshiba();
                }
                if (e.Alt && e.Shift && e.Control && e.KeyCode == Keys.A)
                {
                    AutoGenLstFile = true;
                }
                if (e.Control && e.Alt && e.Shift && e.KeyCode == Keys.N) notConnecttoFPD = true;
                if (isAcq)
                {
                    if (e.KeyCode == Keys.N || e.KeyCode == Keys.E)
                    {
                        try
                        {
                            frm_QuickRegistration newForm = new frm_QuickRegistration(m_intCurrDevice1);
                            newForm.ImgPath = txtImgDir.Text.Trim();
                            newForm.WLDataSource = m_dtWLDataSource;
                            newForm.grdList = grdWorkList;
                            newForm.Act = action.Insert;
                            newForm.ShowDialog();
                            SetSuspendingInfo();
                            if (newForm.IsBeginExam)
                            {
                                ModifyWorkListButtons();
                                BeginExam();
                                ShortCut2AddProc(Last_Anatomy, Last_Projection,true,ref _newDetailID);
                            }
                        }
                        catch
                        {
                        }
                        return;
                    }
                    if (e.KeyCode == Keys.S)
                    {
                        cmdSaveImg_Click(cmdSaveImg, new EventArgs());
                        return;
                    }
                    if (e.KeyCode == Keys.P)
                    {
                        cmdDicomPrinter_Click(cmdDicomPrinter, new EventArgs());
                        return;
                    }
                    if (e.KeyCode == Keys.Left || e.KeyCode == Keys.Right)
                    {
                        cmdFlipV_Click(cmdFlipV, new EventArgs());
                        return;
                    }
                    if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up)
                    {
                        cmdFlipH_Click(cmdFlipH, new EventArgs());
                        return;
                    }
                    if (e.KeyCode == Keys.C )
                    {
                        _DicomMedicalViewer.AutoAddRec4CropWhenPressC();
                        return;
                    }

                    if (e.KeyCode == Keys.R)
                    {
                        ChangeSymBol(_DicomMedicalViewer._medicalViewer, _DicomMedicalViewer._medicalViewerCellIndex, _R);
                        return;
                    }
                    if (e.KeyCode == Keys.L)
                    {
                        ChangeSymBol(_DicomMedicalViewer._medicalViewer, _DicomMedicalViewer._medicalViewerCellIndex, _L);
                        return;
                    }
                    if (e.KeyCode == Keys.U )
                    {
                        ChangeSymBol(_DicomMedicalViewer._medicalViewer, _DicomMedicalViewer._medicalViewerCellIndex, _U);
                        return;
                    }
                    if (e.KeyCode == Keys.B )
                    {
                        ChangeSymBol(_DicomMedicalViewer._medicalViewer, _DicomMedicalViewer._medicalViewerCellIndex, _B);
                        return;
                    }
                    if (e.KeyCode == Keys.O )
                    {
                        AddOtherSymbol();
                        return;
                    }
                }
                if (e.KeyCode == Keys.Enter) ProcessTabKey(true);

                if (_DicomMedicalViewer.IsValidCell())
                {
                    if (e.KeyCode == Keys.Back || e.KeyCode == Keys.F5)
                    {
                        try
                        {
                            using (RasterCodecs _codecs = new RasterCodecs())
                            {
                                //_codecs.Options.Load.DiskMemory = true;
                                RasterImage temp = _codecs.Load(CurrCellFileName);
                                Convert2MedicalViewerCell(_DicomMedicalViewer._medicalViewer.Cells[_DicomMedicalViewer._medicalViewerCellIndex]).Image = temp.CloneAll();
                                _DicomMedicalViewer.try2FreeImage(ref temp);
                            }
                        }
                        catch
                        {
                        }
                    }
                    if (e.Modifiers == Keys.Control && e.KeyCode == Keys.Right)
                    {
                        Rotate(_DicomMedicalViewer._medicalViewer, 90,false);


                    }
                    if (e.Modifiers == Keys.Control && e.KeyCode == Keys.Left)
                    {
                        Rotate(_DicomMedicalViewer._medicalViewer, -90,false);
                    }
                }
                if (e.Modifiers == Keys.Control && (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down))
                {
                    //a.PerformClick();
                }
                if (e.Modifiers == Keys.Alt && (e.KeyCode == Keys.Right || e.KeyCode == Keys.Left))
                {
                    //av.PerformClick();
                }
                if (e.KeyCode == Keys.F12)
                {
                    lstFPD560_DoubleClick(lstFPD560,new EventArgs());
                    //_FullScreen.ShowFullScreen();
                    return;
                }
                if (e.Modifiers == Keys.Control && e.KeyCode == Keys.R)
                {
                    mdlStatic.isDisplayImg=false;
                    isLoadding = false;
                    ViewImg();
                    return;
                }
                if (e.KeyCode == Keys.F2 && !Running)
                {
                    cmdRepeatAcquisition.PerformClick();
                }
                if (e.KeyCode == Keys.N && e.Control && e.Alt)
                {
                    UpdateDiagnostic();
                }
                if (e.KeyCode == Keys.F6)
                {
                    //SetPermission();
                }
                if (e.KeyCode == Keys.Escape && Running)
                {
                    cmdSendtoServer.PerformClick();
                }
                if (e.Modifiers == Keys.Control && (e.KeyCode == Keys.V))
                {
                    //bool FileErr = false;
                    //string Err = "";
                    //System.Collections.Specialized.StringCollection _StrClt = Clipboard.GetFileDropList();
                    //foreach (string s in _StrClt)
                    //{
                    //    try
                    //    {
                    //        OpenDicom(_DicomMedicalViewer._medicalViewer, s);
                    //    }
                    //    catch (Exception ex)
                    //    {
                    //        Err += @"File:" + s + " không hợp lệ!\n";
                    //        FileErr = true;
                    //    }
                    //}
                    //if (FileErr) MessageBox.Show(Err);
                }
            }
            catch
            {
                return;
            }
        }
Exemple #56
0
        private void IntializeAnnContainer()
        {
             SuspendLayout();

            imageViewer = new RasterImageViewer();
             imageViewer.Dock = DockStyle.Fill;
             imageViewer.EnableScrollingInterface = true;
             this.imageViewer.KeyDown += new System.Windows.Forms.KeyEventHandler(this.imageViewer_KeyDown);
             this.imageViewer.DoubleClick += new System.EventHandler(this.imageViewer_Clicked);
            // this.imageViewer.MouseMove += new System.Windows.Forms.MouseEventHandler(this._viewer_MouseMove);
             
             this.Controls.Add(imageViewer);

            

            _automationManager = new AnnAutomationManager();
            _annAutomation = new AnnAutomation(_automationManager, this.imageViewer);
            _annAutomation.Active = true;
            this.imageViewer.BringToFront();
            
            //imageViewer.
            
           
      
            _codec = new RasterCodecs();
            CodecsTxtLoadOptions txtOption = _codec.Options.Txt.Load;
            txtOption.Enabled = true;

            _automationManager.RasterCodecs = _codec;
            _automationManager.RedactionRealizePassword = "";
            _automationManager.CreateDefaultObjects();
            CustomizeObjectProperty();

             
            PropertyForm propForm = new PropertyForm();
            
            _automationManager.ObjectPropertiesDialogType = propForm.GetType();
         //   _automationManager.ObjectPropertiesDialogType = null;
            AddCheckMark(_automationManager);

            _automationManager.CreateToolBar();
            _automationManager.ToolBar.BringToFront();
            imageToolBar = new ImageToolBar();
            this.imageToolBar.TifEditor = this;
            toolBar = imageToolBar.GetExtendedToolBar(_automationManager.ToolBar);
            toolBar.Dock = DockStyle.Bottom;

            this.Controls.Add(_automationManager.ToolBar);




            topToolBar = imageToolBar.AddCustomToolBar(topToolBar);

            
            imageToolBar.UpdateToolBar();
            ResumeLayout();

            RasterPaintProperties prop = imageViewer.PaintProperties;
           // prop.PaintDisplayMode |= RasterPaintDisplayModeFlags.ScaleToGray | RasterPaintDisplayModeFlags.Bicubic;
            prop.PaintDisplayMode = RasterPaintDisplayModeFlags.ScaleToGray;
            imageViewer.PaintProperties = prop;
            

            
            InitialzeEdit();


        }
Exemple #57
0
        private void cmdDicomPrinter_Click(object sender, EventArgs e)
        {
            try
            {
                AutoSaveImgBeforePrint();
                using (RasterCodecs _codecs = new RasterCodecs())
                {
                    using (frm_FilmPrintPreviewV2 _FilmPrintPreview = new frm_FilmPrintPreviewV2(_DicomMedicalViewer, _CurrCell,_AppMode, _codecs, HospitalName, DepartmentName,!chkLeadtoolsPrint.IsChecked))
                    {
                      
                        _FilmPrintPreview.m_dtDicomconverterInfo = m_dtDicomconverterInfo.Clone();
                        _FilmPrintPreview._paintProperties = _paintProperties;
                        _FilmPrintPreview.RegNumber2 = txtRegNumber2.Text.Trim();
                        _FilmPrintPreview.ImgDir = txtImgDir.Text.Trim() + @"\" + SubDirLv1() + @"\" + SubDirLv2_Patient();
                        _FilmPrintPreview.HosName =Bodau( HospitalName);
                        _FilmPrintPreview.DepartName =Bodau( DepartmentName);
                        _FilmPrintPreview.Reg_ID = currREGID;
                        _FilmPrintPreview.ShowDialog(this);
                        if (_FilmPrintPreview._ApplicationMustbeExisted)
                            Application.Exit();
                        else
                            try2ResetScheduledStatus(_FilmPrintPreview.htbDetail);
                    }
                }

            }
            catch
            {
            }
            finally
            {

            }
        }