Пример #1
0
        /// <summary>
        /// アプリケーションの初期化処理を行います。
        /// </summary>
        private void InitClass()
        {
            // フォームのタイトルを設定します。
            this.Text = "TWAIN 取得 【振替伝票読み取り】";

            //自分自身のバージョン情報を取得する 2011/03/25
            //System.Diagnostics.FileVersionInfo ver =
            //    System.Diagnostics.FileVersionInfo.GetVersionInfo(
            //    System.Reflection.Assembly.GetExecutingAssembly().Location);

            //キャプションにバージョンを追加 2011/03/25
            //Messager.Caption += " ver " + ver.FileMajorPart.ToString() + "." + ver.FileMinorPart.ToString();

            //Text = Messager.Caption;

            // ロック解除状態を確認します。
            //Support.Unlock(false);

            // RasterImageViewerコントロールを初期化します。
            _viewer = new RasterImageViewer();
            //_viewer.Dock = DockStyle.Fill;
            _viewer.BackColor = Color.DarkGray;
            Controls.Add(_viewer);
            _viewer.BringToFront();
            _viewer.Visible = false;

            // コーデックパスを設定します。
            RasterCodecs.Startup();

            // RasterCodecsオブジェクトを初期化します。
            _codecs = new RasterCodecs();

            if (TwainSession.IsAvailable(this))
            {
                // TwainSessionオブジェクトを初期化します。
                _twainSession = new TwainSession();

                // TWAIN セッションを初期化します。
                _twainSession.Startup(this, "FKDL", "LEADTOOLS", "Ver16.5J", "OCR", TwainStartupFlags.None);
                //_twainSession.Startup2(this, "FKDL", "LEADTOOLS", "Ver16.5J", "OCR", TwainStartupFlags.None, TwainLanguage.LanguageJapanese, TwainCountry.CountryJapan);
            }
            else
            {
                //_miFileAcquire.Enabled = false;
                //_miFileSelectSource.Enabled = false;
            }

            // 各値を初期化します。
            _fileName    = string.Empty;
            _fileFormat  = RasterImageFormat.Tif;
            _pageNo      = 1;
            _sFileNumber = 0;

            //UpdateMyControls();
            UpdateStatusBarText();
        }
Пример #2
0
 public void SaveStreamToJpeg(Stream sourceImage, string imageName)
 {
     try
     {
         RasterCodecs.Startup();
         rasterCodecs = new RasterCodecs();
         img          = rasterCodecs.Load(sourceImage);
         Leadtools.RasterImageFormat rif = Leadtools.RasterImageFormat.Jpeg;
         rasterCodecs.Save(img, imageName, rif, img.BitsPerPixel);
     }
     finally
     {
         img.Dispose();
         RasterCodecs.Shutdown();
     }
 }
Пример #3
0
        ///----------------------------------------------------------------
        /// <summary>
        ///     伝票画像表示 </summary>
        /// <param name="iX">
        ///     現在の伝票</param>
        /// <param name="tempImgName">
        ///     画像名</param>
        ///----------------------------------------------------------------
        public void ShowImage(string tempImgName)
        {
            //string wrkFileName;

            //修正画面へ組み入れた画像フォームの表示
            //画像の出力が無い場合は、画像表示をしない。
            if (tempImgName == string.Empty)
            {
                leadImg.Visible = false;
                //global.pblImageFile = string.Empty;
                return;
            }

            //画像ファイルがあるときのみ表示
            //wrkFileName = tempImgName;
            if (System.IO.File.Exists(tempImgName))
            {
                leadImg.Visible = true;

                //画像ロード
                RasterCodecs.Startup();
                RasterCodecs cs = new RasterCodecs();

                // 描画時に使用される速度、品質、およびスタイルを制御します。
                RasterPaintProperties prop = new RasterPaintProperties();
                prop = RasterPaintProperties.Default;
                prop.PaintDisplayMode   = RasterPaintDisplayModeFlags.Resample;
                leadImg.PaintProperties = prop;

                leadImg.Image = cs.Load(tempImgName, 0, CodecsLoadByteOrder.BgrOrGray, 1, 1);

                //画像表示倍率設定
                if (gl.miMdlZoomRate == 0f)
                {
                    if (leadImg.ImageDpiX == 200)
                    {
                        leadImg.ScaleFactor *= gl.ZOOM_RATE;    // 200*200 画像のとき
                    }
                    else
                    {
                        leadImg.ScaleFactor *= gl.ZOOM_RATE;        // 300*300 画像のとき
                    }
                }
                else
                {
                    leadImg.ScaleFactor *= gl.miMdlZoomRate;
                }

                //画像のマウスによる移動を可能とする
                leadImg.InteractiveMode = RasterViewerInteractiveMode.Pan;

                ////右へ90°回転させる
                //RotateCommand rc = new RotateCommand();
                //rc.Angle = 90 * 100;
                //rc.FillColor = new RasterColor(255, 255, 255);
                ////rc.Flags = RotateCommandFlags.Bicubic;
                //rc.Flags = RotateCommandFlags.Resize;
                //rc.Run(leadImg.Image);

                // グレースケールに変換
                GrayscaleCommand grayScaleCommand = new GrayscaleCommand();
                grayScaleCommand.BitsPerPixel = 8;
                grayScaleCommand.Run(leadImg.Image);
                leadImg.Refresh();

                cs.Dispose();
                RasterCodecs.Shutdown();
                //global.pblImageFile = wrkFileName;

                // 画像操作ボタン
                btnPlus.Enabled  = true;
                btnMinus.Enabled = true;
            }
            else
            {
                //画像ファイルがないとき
                leadImg.Visible = false;
                //global.pblImageFile = string.Empty;

                // 画像操作ボタン
                btnPlus.Enabled  = false;
                btnMinus.Enabled = false;
            }
        }
Пример #4
0
        /// <summary>
        /// OCR処理を実施します
        /// </summary>
        /// <param name="InPath">入力パス</param>
        /// <param name="NgPath">NG出力パス</param>
        /// <param name="rePath">OCR変換結果出力パス</param>
        /// <param name="FormatName">書式ファイル名</param>
        /// <param name="fCnt">書式ファイルの件数</param>
        private void ocrMain(string InPath, string NgPath, string rePath, string FormatName, int fCnt)
        {
            IEngine en       = null;            // OCRエンジンのインスタンスを保持
            string  ocr_csv  = string.Empty;    // OCR変換出力CSVファイル
            int     _okCount = 0;               // OCR変換画像枚数
            int     _ngCount = 0;               // フォーマットアンマッチ画像枚数
            string  fnm      = string.Empty;    // ファイル名

            try
            {
                // 指定された出力先フォルダがなければ作成する
                if (System.IO.Directory.Exists(rePath) == false)
                {
                    System.IO.Directory.CreateDirectory(rePath);
                }

                // 指定されたNGの場合の出力先フォルダがなければ作成する
                if (System.IO.Directory.Exists(NgPath) == false)
                {
                    System.IO.Directory.CreateDirectory(NgPath);
                }

                // OCRエンジンのインスタンスの生成・取得
                en = EngineFactory.GetEngine();
                if (en == null)
                {
                    // エンジンが他で取得されている場合は、Release() されるまで取得できない
                    System.Console.WriteLine("SDKは使用中です");
                    return;
                }

                //オーナーフォームを無効にする
                this.Enabled = false;

                //プログレスバーを表示する
                frmPrg frmP = new frmPrg();
                frmP.Owner = this;
                frmP.Show();

                IFormatList FormatList;
                IFormat     Format;
                IField      Field;
                int         nPage;
                int         ocrPage   = 0;
                int         fileCount = 0;

                // フォーマットのロード・設定
                FormatList = en.FormatList;
                FormatList.Add(FormatName);

                // tifファイルの認識
                foreach (string files in System.IO.Directory.GetFiles(InPath, "*.tif"))
                {
                    nPage = 1;
                    while (true)
                    {
                        try
                        {
                            // 対象画像を設定する
                            en.SetBitmap(files, nPage);

                            //プログレスバー表示
                            fileCount++;
                            frmP.Text          = "OCR変換処理実行中 " + fileCount.ToString() + "/" + fCnt.ToString();
                            frmP.progressValue = fileCount * 100 / fCnt;
                            frmP.ProgressStep();
                        }
                        catch (IDRException ex)
                        {
                            // ページ読み込みエラー
                            if (ex.No == ErrorCode.IDR_ERROR_FORM_FILEREAD)
                            {
                                // ページの終了
                                break;
                            }
                            else
                            {
                                // 例外のキャッチ
                                MessageBox.Show("例外が発生しました:Error No ={0:X}", ex.No.ToString());
                            }
                        }

                        //////Console.WriteLine("-----" + strImageFile + "の" + nPage + "ページ-----");
                        // 現在ロードされている画像を自動的に傾き補正する
                        en.AutoSkew();

                        // 傾き角度の取得
                        double angle = en.GetSkewAngle();
                        //////System.Console.WriteLine("時計回りに" + angle + "度傾き補正を行いました");

                        try
                        {
                            // 現在ロードされている画像を自動回転してマッチする番号を取得する
                            Format = en.MatchFormatRotate();
                            int direct = en.GetRotateAngle();

                            //画像ロード
                            RasterCodecs.Startup();
                            RasterCodecs cs = new RasterCodecs();
                            //RasterImage img;

                            // 描画時に使用される速度、品質、およびスタイルを制御します。
                            //RasterPaintProperties prop = new RasterPaintProperties();
                            //prop = RasterPaintProperties.Default;
                            //prop.PaintDisplayMode = RasterPaintDisplayModeFlags.Resample;
                            //leadImg.PaintProperties = prop;

                            RasterImage img = cs.Load(files, 0, CodecsLoadByteOrder.BgrOrGray, 1, 1);

                            RotateCommand rc = new RotateCommand();
                            rc.Angle     = (direct) * 90 * 100;
                            rc.FillColor = new RasterColor(255, 255, 255);
                            rc.Flags     = RotateCommandFlags.Resize;
                            rc.Run(img);
                            //rc.Run(leadImg.Image);

                            //cs.Save(leadImg.Image, files, RasterImageFormat.Tif, 0, 1, 1, 1, CodecsSavePageMode.Overwrite);
                            cs.Save(img, files, RasterImageFormat.CcittGroup4, 0, 1, 1, 1, CodecsSavePageMode.Overwrite);

                            // マッチしたフォーマットに登録されているフィールド数を取得
                            int fieldNum = Format.NumOfFields;
                            int matchNum = Format.FormatNo + 1;
                            //////System.Console.WriteLine(matchNum + "番目のフォーマットがマッチ");
                            int i = 1;
                            ocr_csv = string.Empty;

                            // ファイルの先頭フィールドにファイル番号をセットします
                            ocr_csv = System.IO.Path.GetFileNameWithoutExtension(files) + ",";

                            // ファイルに画像ファイル名フィールドを付加します
                            ocr_csv += System.IO.Path.GetFileName(files);

                            // 認識されたフィールドを順次読み出します
                            Field = Format.Begin();
                            while (Field != null)
                            {
                                //カンマ付加
                                if (ocr_csv != string.Empty)
                                {
                                    ocr_csv += ",";
                                }

                                // 指定フィールドを認識し、テキストを取得
                                string strText = Field.ExtractFieldText();
                                ocr_csv += strText;

                                // 次のフィールドの取得
                                Field = Format.Next();
                                i    += 1;
                            }

                            //出力ファイル
                            System.IO.StreamWriter outFile = new System.IO.StreamWriter(InPath + System.IO.Path.GetFileNameWithoutExtension(files) + ".csv", false, System.Text.Encoding.GetEncoding(932));
                            outFile.WriteLine(ocr_csv);
                            outFile.Close();

                            //OCR変換枚数カウント
                            _okCount++;
                        }
                        catch (IDRWarning ex)
                        {
                            // Engine.MatchFormatRotate() で
                            // フォーマットにマッチしなかった場合の処理
                            if (ex.No == ErrorCode.IDR_WARN_FORM_NO_MATCH)
                            {
                                // NGフォルダへ移動する
                                System.IO.File.Move(files, NgPath + "E" + System.IO.Path.GetFileName(files));

                                //NG枚数カウント
                                _ngCount++;
                            }
                        }

                        ocrPage++;
                        nPage += 1;
                    }
                }

                // いったんオーナーをアクティブにする
                this.Activate();

                // 進行状況ダイアログを閉じる
                frmP.Close();

                // オーナーのフォームを有効に戻す
                this.Enabled = true;

                string        finMessage = string.Empty;
                StringBuilder sb         = new StringBuilder();

                // NGメッセージ
                if (_ngCount > 0)
                {
                    MessageBox.Show("OCR認識を正常に行うことが出来なかった画像があります。確認してください。", "確認", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                // 終了メッセージ
                sb.Clear();
                sb.Append("OCR認識処理が終了しました。");
                sb.Append("引き続き修正確認&受け渡しデータ作成を行ってください。");
                sb.Append(Environment.NewLine);
                sb.Append(Environment.NewLine);
                sb.Append("OK件数 : ");
                sb.Append(_okCount.ToString());
                sb.Append(Environment.NewLine);
                sb.Append("NG件数 : ");
                sb.Append(_ngCount.ToString());
                sb.Append(Environment.NewLine);

                MessageBox.Show(sb.ToString(), "処理終了", MessageBoxButtons.OK, MessageBoxIcon.Information);
                // OCR変換画像とCSVデータをOCR結果出力フォルダへ移動する
                foreach (string files in System.IO.Directory.GetFiles(InPath, "*.*"))
                {
                    System.IO.File.Move(files, rePath + System.IO.Path.GetFileName(files));
                }

                FormatList.Delete(0);
            }
            catch (System.Exception ex)
            {
                // 例外のキャッチ
                string errMessage = string.Empty;
                errMessage += "System例外が発生しました:" + Environment.NewLine;
                errMessage += "必要なDLL等が実行モジュールと同ディレクトリに存在するか確認してください。:" + Environment.NewLine;
                errMessage += ex.Message.ToString();
                MessageBox.Show(errMessage, "エラー", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            finally
            {
                en.Release();
            }
        }
Пример #5
0
        /// <summary>
        /// マルチフレームの画像ファイルを頁ごとに分割する
        /// </summary>
        /// <param name="InPath">画像ファイルパス</param>
        private void MultiTif(int ocrSel, string InPath, string WrkPath)
        {
            //スキャン出力画像を確認
            string[] intif = System.IO.Directory.GetFiles(InPath, "*.tif");
            if (intif.Length == 0)
            {
                MessageBox.Show("OCR変換処理対象の画像ファイルが指定フォルダ " + InPath + " に存在しません", "スキャナ画像確認", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            // READフォルダがなければ作成する
            string rPath = Properties.Settings.Default.PathInst + Properties.Settings.Default.PathREAD;

            if (System.IO.Directory.Exists(rPath) == false)
            {
                System.IO.Directory.CreateDirectory(rPath);
            }

            // READフォルダ内の全てのファイルを削除する(通常ファイルは存在しないが例外処理などで残ってしまった場合に備えて念のため)
            foreach (string files in System.IO.Directory.GetFiles(rPath, "*"))
            {
                System.IO.File.Delete(files);
            }

            // FAX画像処理時にWORKフォルダがなければ作成する
            if (ocrSel == global.FAX_SELECT)
            {
                if (System.IO.Directory.Exists(WrkPath) == false)
                {
                    System.IO.Directory.CreateDirectory(WrkPath);
                }

                // WORKフォルダ内の全てのファイルを削除する(通常ファイルは存在しないが例外処理などで残ってしまった場合に備えて念のため)
                foreach (string files in System.IO.Directory.GetFiles(WrkPath, "*"))
                {
                    System.IO.File.Delete(files);
                }
            }

            RasterCodecs.Startup();
            RasterCodecs cs = new RasterCodecs();

            _pageNo = 0;
            string fnm = string.Empty;

            // 1.マルチTIFを分解して画像ファイルをREADフォルダかWorkフォルダへ保存する
            foreach (string files in System.IO.Directory.GetFiles(InPath, "*.tif"))
            {
                // 画像読み出す
                RasterImage leadImg = cs.Load(files, 0, CodecsLoadByteOrder.BgrOrGray, 1, -1);

                // 頁数を取得
                int _fd_count = leadImg.PageCount;

                // 頁ごとに読み出す
                for (int i = 1; i <= _fd_count; i++)
                {
                    // ファイル名(日付時間部分)
                    string fName = string.Format("{0:0000}", DateTime.Today.Year) +
                                   string.Format("{0:00}", DateTime.Today.Month) +
                                   string.Format("{0:00}", DateTime.Today.Day) +
                                   string.Format("{0:00}", DateTime.Now.Hour) +
                                   string.Format("{0:00}", DateTime.Now.Minute) +
                                   string.Format("{0:00}", DateTime.Now.Second);

                    // ファイル名設定
                    _pageNo++;

                    if (ocrSel == global.SCAN_SELECT)
                    {
                        fnm = rPath + fName + string.Format("{0:000}", _pageNo) + ".tif";   // SCANのときREADフォルダへ出力
                    }
                    else
                    {
                        fnm = WrkPath + fName + string.Format("{0:000}", _pageNo) + ".tif";     // スキャナのときWORKフォルダへ出力
                    }
                    // 画像保存
                    cs.Save(leadImg, fnm, RasterImageFormat.CcittGroup4, 0, i, i, 1, CodecsSavePageMode.Insert);
                }
            }

            // 2.InPathフォルダの全てのtifファイルを削除する
            foreach (var files in System.IO.Directory.GetFiles(InPath, "*.tif"))
            {
                System.IO.File.Delete(files);
            }

            // 3.FAX画像解像度の調整
            if (_OcrSel == global.FAX_SELECT)
            {
                foreach (string files in System.IO.Directory.GetFiles(WrkPath, "*.tif"))
                {
                    ////// 描画時に使用される速度、品質、およびスタイルを制御します。
                    ////RasterPaintProperties prop = new RasterPaintProperties();
                    ////prop = RasterPaintProperties.Default;
                    ////prop.PaintDisplayMode = RasterPaintDisplayModeFlags.Resample;
                    ////leadImg.PaintProperties = prop;

                    // 画像読み出す
                    RasterImage leadImg = cs.Load(files, 0, CodecsLoadByteOrder.BgrOrGray, 1, -1);

                    // 画像リサイズ(DPI:X:200,Y:200)
                    ResizeCommand rs = new ResizeCommand();
                    rs.DestinationImage             = leadImg;
                    rs.DestinationImage.XResolution = 200;
                    rs.DestinationImage.YResolution = 200;
                    rs.Flags = RasterSizeFlags.None;
                    rs.Run(leadImg);

                    // A4サイズへ変更
                    Leadtools.ImageProcessing.SizeCommand sz = new SizeCommand();
                    sz.Width  = 1693;
                    sz.Height = 2338;
                    sz.Run(leadImg);

                    // 画像保存
                    cs.Save(leadImg, files, RasterImageFormat.Tif, 0, 1, -1, 1, CodecsSavePageMode.Overwrite);
                }

                // 変換済みtif画像をREADフォルダへ移動する
                foreach (string files in System.IO.Directory.GetFiles(WrkPath, "*.tif"))
                {
                    System.IO.File.Move(files, rPath + "\\" + System.IO.Path.GetFileName(files));
                }
            }
        }
Пример #6
0
        /// <summary>
        /// マルチフレームの画像ファイルを頁ごとに分割する
        /// </summary>
        /// <param name="InPath">画像ファイルパス</param>
        private void MultiTif(string InPath)
        {
            //スキャン出力画像を確認
            string[] intif = System.IO.Directory.GetFiles(InPath, "*.tif");
            if (intif.Length == 0)
            {
                MessageBox.Show("OCR変換処理対象の勤務票の画像ファイルが指定フォルダ " + InPath + " に存在しません", "スキャナ画像確認", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            // READフォルダがなければ作成する
            string rPath = Properties.Settings.Default.instPath + Properties.Settings.Default.readPath;

            if (System.IO.Directory.Exists(rPath) == false)
            {
                System.IO.Directory.CreateDirectory(rPath);
            }

            // READフォルダ内の全てのファイルを削除する(通常ファイルは存在しないが例外処理などで残ってしまった場合に備えて念のため)
            foreach (string files in System.IO.Directory.GetFiles(rPath, "*"))
            {
                System.IO.File.Delete(files);
            }

            RasterCodecs.Startup();
            RasterCodecs cs = new RasterCodecs();

            _pageNo = 0;
            string fnm = string.Empty;

            // 1.マルチTIFを分解して画像ファイルをREADフォルダへ保存する
            foreach (string files in System.IO.Directory.GetFiles(InPath, "*.tif"))
            {
                // 画像読み出す
                RasterImage leadImg = cs.Load(files, 0, CodecsLoadByteOrder.BgrOrGray, 1, -1);

                // 頁数を取得
                int _fd_count = leadImg.PageCount;

                // 頁ごとに読み出す
                for (int i = 1; i <= _fd_count; i++)
                {
                    // ファイル名(日付時間部分)
                    string fName = string.Format("{0:0000}", DateTime.Today.Year) +
                                   string.Format("{0:00}", DateTime.Today.Month) +
                                   string.Format("{0:00}", DateTime.Today.Day) +
                                   string.Format("{0:00}", DateTime.Now.Hour) +
                                   string.Format("{0:00}", DateTime.Now.Minute) +
                                   string.Format("{0:00}", DateTime.Now.Second);

                    // ファイル名設定
                    _pageNo++;
                    fnm = rPath + fName + string.Format("{0:000}", _pageNo) + ".tif";

                    // 画像保存
                    cs.Save(leadImg, fnm, RasterImageFormat.CcittGroup4, 0, i, i, 1, CodecsSavePageMode.Insert);
                }
            }

            // 2.InPathフォルダの全てのtifファイルを削除する
            foreach (var files in System.IO.Directory.GetFiles(InPath, "*.tif"))
            {
                System.IO.File.Delete(files);
            }
        }
Пример #7
0
        ///------------------------------------------------------------------------------
        /// <summary>
        ///     画像の解像度とサイズを変更する </summary>
        /// <param name="InPath">
        ///     画像ファイル入力パス</param>
        /// <returns>
        ///     true:分割を実施, false:分割ファイルなし</returns>
        ///------------------------------------------------------------------------------
        private bool imageResize(string InPath)
        {
            // 画像を確認
            if (System.IO.Directory.GetFiles(InPath, "*.tif").Count() == 0)
            {
                return(false);
            }

            RasterCodecs.Startup();
            RasterCodecs cs = new RasterCodecs();

            string fnm = string.Empty;

            //コマンドを準備します。(傾き・ノイズ除去・リサイズ)
            DeskewCommand    Dcommand  = new DeskewCommand();
            DespeckleCommand Dkcommand = new DespeckleCommand();
            SizeCommand      Rcommand  = new SizeCommand();

            // オーナーフォームを無効にする
            this.Enabled = false;

            //プログレスバーを表示する
            frmPrg frmP = new frmPrg();

            frmP.Owner = this;
            frmP.Show();

            int cImg = System.IO.Directory.GetFiles(InPath, "*.tif").Count();
            int cCnt = 0;

            foreach (string files in System.IO.Directory.GetFiles(InPath, "*.tif"))
            {
                cCnt++;

                //プログレスバー表示
                frmP.Text          = "OCR変換画像データロード中 " + cCnt.ToString() + "/" + cImg;
                frmP.progressValue = cCnt * 100 / cImg;
                frmP.ProgressStep();

                // 画像読み出す
                RasterImage leadImg = cs.Load(files, 0, CodecsLoadByteOrder.BgrOrGray, 1, -1);

                //画像補正処理 開始 ↓ ****************************
                try
                {
                    //画像の傾きを補正します。
                    Dcommand.Flags = DeskewCommandFlags.DeskewImage | DeskewCommandFlags.DoNotFillExposedArea;
                    Dcommand.Run(leadImg);
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(i + "画像の傾き補正エラー:" + ex.Message);
                }

                //ノイズ除去
                try
                {
                    Dkcommand.Run(leadImg);
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(i + "ノイズ除去エラー:" + ex.Message);
                }

                //解像度調整(200*200dpi)
                leadImg.XResolution = 200;
                leadImg.YResolution = 200;

                //A4縦サイズに変換(ピクセル単位)
                Rcommand.Width  = 1637;
                Rcommand.Height = 2322;
                try
                {
                    Rcommand.Run(leadImg);
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(i + "解像度調整エラー:" + ex.Message);
                }

                //画像補正処理 終了↑ ****************************

                // 画像保存
                cs.Save(leadImg, files, RasterImageFormat.Tif, 0, 1, 1, 1, CodecsSavePageMode.Overwrite);
            }

            //LEADTOOLS入出力ライブラリを終了します。
            RasterCodecs.Shutdown();

            // いったんオーナーをアクティブにする
            this.Activate();

            // 進行状況ダイアログを閉じる
            frmP.Close();

            // オーナーのフォームを有効に戻す
            this.Enabled = true;

            return(true);
        }
Пример #8
0
        ///------------------------------------------------------------------------------
        /// <summary>
        ///     マルチフレームの画像ファイルを頁ごとに分割する </summary>
        /// <param name="InPath">
        ///     画像ファイル入力パス</param>
        /// <param name="outPath">
        ///     分割後出力パス</param>
        /// <returns>
        ///     true:分割を実施, false:分割ファイルなし</returns>
        ///------------------------------------------------------------------------------
        private bool MultiTif(string InPath, string outPath, string fName)
        {
            //スキャン出力画像を確認
            if (System.IO.Directory.GetFiles(InPath, "*.tif").Count() == 0)
            {
                return(false);
            }

            // 出力先フォルダがなければ作成する
            if (System.IO.Directory.Exists(outPath) == false)
            {
                System.IO.Directory.CreateDirectory(outPath);
            }

            // 出力先フォルダ内の全てのファイルを削除する(通常ファイルは存在しないが例外処理などで残ってしまった場合に備えて念のため)
            foreach (string files in System.IO.Directory.GetFiles(outPath, "*"))
            {
                System.IO.File.Delete(files);
            }

            RasterCodecs.Startup();
            RasterCodecs cs = new RasterCodecs();

            int    _pageCount = 0;
            string fnm        = string.Empty;

            //コマンドを準備します。(傾き・ノイズ除去・リサイズ)
            DeskewCommand    Dcommand  = new DeskewCommand();
            DespeckleCommand Dkcommand = new DespeckleCommand();
            SizeCommand      Rcommand  = new SizeCommand();

            // オーナーフォームを無効にする
            this.Enabled = false;

            //プログレスバーを表示する
            frmPrg frmP = new frmPrg();

            frmP.Owner = this;
            frmP.Show();

            int cImg = System.IO.Directory.GetFiles(InPath, "*.tif").Count();
            int cCnt = 0;

            // マルチTIFを分解して画像ファイルをTRAYフォルダへ保存する
            foreach (string files in System.IO.Directory.GetFiles(InPath, "*.tif"))
            {
                cCnt++;

                //プログレスバー表示
                frmP.Text          = "OCR変換画像データロード中 " + cCnt.ToString() + "/" + cImg;
                frmP.progressValue = cCnt * 100 / cImg;
                frmP.ProgressStep();

                // 画像読み出す
                RasterImage leadImg = cs.Load(files, 0, CodecsLoadByteOrder.BgrOrGray, 1, -1);

                // 頁数を取得
                int _fd_count = leadImg.PageCount;

                // 頁ごとに読み出す
                for (int i = 1; i <= _fd_count; i++)
                {
                    //ページを移動する
                    leadImg.Page = i;

                    // ファイル名設定
                    _pageCount++;
                    fnm = outPath + fName + string.Format("{0:000}", _pageCount) + ".tif";

                    //画像補正処理 開始 ↓ ****************************
                    try
                    {
                        //画像の傾きを補正します。
                        Dcommand.Flags = DeskewCommandFlags.DeskewImage | DeskewCommandFlags.DoNotFillExposedArea;
                        Dcommand.Run(leadImg);
                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show(i + "画像の傾き補正エラー:" + ex.Message);
                    }

                    //ノイズ除去
                    try
                    {
                        Dkcommand.Run(leadImg);
                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show(i + "ノイズ除去エラー:" + ex.Message);
                    }

                    //解像度調整(200*200dpi)
                    leadImg.XResolution = 200;
                    leadImg.YResolution = 200;

                    //A4縦サイズに変換(ピクセル単位)
                    Rcommand.Width  = 1637;
                    Rcommand.Height = 2322;
                    try
                    {
                        Rcommand.Run(leadImg);
                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show(i + "解像度調整エラー:" + ex.Message);
                    }

                    //画像補正処理 終了↑ ****************************

                    // 画像保存
                    cs.Save(leadImg, fnm, RasterImageFormat.Tif, 0, i, i, 1, CodecsSavePageMode.Insert);
                }
            }

            //LEADTOOLS入出力ライブラリを終了します。
            RasterCodecs.Shutdown();

            // InPathフォルダの全てのtifファイルを削除する
            foreach (var files in System.IO.Directory.GetFiles(InPath, "*.tif"))
            {
                System.IO.File.Delete(files);
            }

            // いったんオーナーをアクティブにする
            this.Activate();

            // 進行状況ダイアログを閉じる
            frmP.Close();

            // オーナーのフォームを有効に戻す
            this.Enabled = true;

            return(true);
        }
Пример #9
0
        ///------------------------------------------------------------------------------
        /// <summary>
        ///     マルチフレームの画像ファイルを頁ごとに分割する </summary>
        /// <param name="InPath">
        ///     画像ファイル入力パス</param>
        /// <param name="outPath">
        ///     分割後出力パス</param>
        /// <returns>
        ///     true:分割を実施, false:分割ファイルなし</returns>
        ///------------------------------------------------------------------------------
        private bool MultiTif(string InPath, string outPath)
        {
            //スキャン出力画像を確認
            if (System.IO.Directory.GetFiles(InPath, "*.tif").Count() == 0)
            {
                MessageBox.Show("OCR変換処理対象の画像ファイルが指定フォルダ " + InPath + " に存在しません", "スキャン画像確認", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return(false);
            }

            // 出力先フォルダがなければ作成する
            if (System.IO.Directory.Exists(outPath) == false)
            {
                System.IO.Directory.CreateDirectory(outPath);
            }

            // 出力先フォルダ内の全てのファイルを削除する(通常ファイルは存在しないが例外処理などで残ってしまった場合に備えて念のため)
            foreach (string files in System.IO.Directory.GetFiles(outPath, "*"))
            {
                System.IO.File.Delete(files);
            }

            RasterCodecs.Startup();
            RasterCodecs cs = new RasterCodecs();

            int    _pageCount = 0;
            string fnm        = string.Empty;

            // マルチTIFを分解して画像ファイルをTRAYフォルダへ保存する
            foreach (string files in System.IO.Directory.GetFiles(InPath, "*.tif"))
            {
                // 画像読み出す
                RasterImage leadImg = cs.Load(files, 0, CodecsLoadByteOrder.BgrOrGray, 1, -1);

                // 頁数を取得
                int _fd_count = leadImg.PageCount;

                // 頁ごとに読み出す
                for (int i = 1; i <= _fd_count; i++)
                {
                    // ファイル名(日付時間部分)
                    string fName = string.Format("{0:0000}", DateTime.Today.Year) +
                                   string.Format("{0:00}", DateTime.Today.Month) +
                                   string.Format("{0:00}", DateTime.Today.Day) +
                                   string.Format("{0:00}", DateTime.Now.Hour) +
                                   string.Format("{0:00}", DateTime.Now.Minute) +
                                   string.Format("{0:00}", DateTime.Now.Second);

                    // ファイル名設定
                    _pageCount++;
                    fnm = outPath + fName + string.Format("{0:000}", _pageCount) + ".tif";

                    // 画像保存
                    cs.Save(leadImg, fnm, RasterImageFormat.Tif, 0, i, i, 1, CodecsSavePageMode.Insert);
                }
            }

            // InPathフォルダの全てのtifファイルを削除する
            foreach (var files in System.IO.Directory.GetFiles(InPath, "*.tif"))
            {
                System.IO.File.Delete(files);
            }

            return(true);
        }
Пример #10
0
        /// <summary>
        /// OCR処理を実施します
        /// </summary>
        /// <param name="InPath">入力パス</param>
        /// <param name="NgPath">NG出力パス</param>
        /// <param name="rePath">OCR変換結果出力パス</param>
        /// <param name="FormatName">書式ファイル名</param>
        /// <param name="fCnt">書式ファイルの件数</param>
        private void ocrMain(string InPath, string NgPath, string rePath, string FormatName, int fCnt)
        {
            IEngine en        = null;                                                // OCRエンジンのインスタンスを保持
            string  ocr_csv   = string.Empty;                                        // OCR変換出力CSVファイル
            int     _ngCount  = 0;                                                   // フォーマットアンマッチ画像枚数
            string  fnm       = string.Empty;                                        // ファイル名
            string  path2Fdir = Properties.Settings.Default.instDir + global.DIR_2F; // 2F伝票フォルダ

            try
            {
                // 指定された出力先フォルダがなければ作成する
                if (System.IO.Directory.Exists(rePath) == false)
                {
                    System.IO.Directory.CreateDirectory(rePath);
                }

                // 指定されたNGの場合の出力先フォルダがなければ作成する
                if (System.IO.Directory.Exists(NgPath) == false)
                {
                    System.IO.Directory.CreateDirectory(NgPath);
                }

                // 2F伝票フォルダがなければ作成する
                if (System.IO.Directory.Exists(path2Fdir) == false)
                {
                    System.IO.Directory.CreateDirectory(path2Fdir);
                }

                // OCRエンジンのインスタンスの生成・取得
                en = EngineFactory.GetEngine();
                if (en == null)
                {
                    // エンジンが他で取得されている場合は、Release() されるまで取得できない
                    System.Console.WriteLine("SDKは使用中です");
                    return;
                }

                //オーナーフォームを無効にする
                this.Enabled = false;

                //プログレスバーを表示する
                frmPrg frmP = new frmPrg();
                frmP.Owner = this;
                frmP.Show();

                IFormatList FormatList;
                IFormat     Format;
                IField      Field;
                int         nPage;
                int         ocrPage   = 0;
                int         fileCount = 0;

                // フォーマットのロード・設定
                FormatList = en.FormatList;
                FormatList.Add(FormatName);

                // tifファイルの認識
                foreach (string files in System.IO.Directory.GetFiles(InPath, "*.tif"))
                {
                    nPage = 1;
                    while (true)
                    {
                        try
                        {
                            // 対象画像を設定する
                            en.SetBitmap(files, nPage);

                            //プログレスバー表示
                            fileCount++;
                            frmP.Text          = "OCR変換処理実行中 " + fileCount.ToString() + "/" + fCnt.ToString();
                            frmP.progressValue = fileCount * 100 / fCnt;
                            frmP.ProgressStep();
                        }
                        catch (IDRException ex)
                        {
                            // ページ読み込みエラー
                            if (ex.No == ErrorCode.IDR_ERROR_FORM_FILEREAD)
                            {
                                // ページの終了
                                break;
                            }
                            else
                            {
                                // 例外のキャッチ
                                MessageBox.Show("例外が発生しました:Error No ={0:X}", ex.No.ToString());
                            }
                        }

                        //////Console.WriteLine("-----" + strImageFile + "の" + nPage + "ページ-----");
                        // 現在ロードされている画像を自動的に傾き補正する
                        en.AutoSkew();

                        // 傾き角度の取得
                        double angle = en.GetSkewAngle();
                        //////System.Console.WriteLine("時計回りに" + angle + "度傾き補正を行いました");

                        try
                        {
                            // 現在ロードされている画像を自動回転してマッチする番号を取得する
                            Format = en.MatchFormatRotate();
                            int direct = en.GetRotateAngle();

                            //画像ロード
                            RasterCodecs.Startup();
                            RasterCodecs cs = new RasterCodecs();
                            //RasterImage img;

                            // 描画時に使用される速度、品質、およびスタイルを制御します。
                            //RasterPaintProperties prop = new RasterPaintProperties();
                            //prop = RasterPaintProperties.Default;
                            //prop.PaintDisplayMode = RasterPaintDisplayModeFlags.Resample;
                            //leadImg.PaintProperties = prop;

                            RasterImage img = cs.Load(files, 0, CodecsLoadByteOrder.BgrOrGray, 1, 1);

                            RotateCommand rc = new RotateCommand();
                            rc.Angle     = (direct) * 90 * 100;
                            rc.FillColor = new RasterColor(255, 255, 255);
                            rc.Flags     = RotateCommandFlags.Resize;
                            rc.Run(img);
                            //rc.Run(leadImg.Image);

                            //cs.Save(leadImg.Image, files, RasterImageFormat.Tif, 0, 1, 1, 1, CodecsSavePageMode.Overwrite);
                            cs.Save(img, files, RasterImageFormat.CcittGroup4, 0, 1, 1, 1, CodecsSavePageMode.Overwrite);

                            // マッチしたフォーマットに登録されているフィールド数を取得
                            int fieldNum = Format.NumOfFields;
                            int matchNum = Format.FormatNo + 1;
                            //////System.Console.WriteLine(matchNum + "番目のフォーマットがマッチ");
                            int i      = 1;
                            int fIndex = 0;
                            ocr_csv = "*,";

                            // ファイルに画像ファイル名フィールドを付加します
                            ocr_csv += System.IO.Path.GetFileName(files);

                            // 認識されたフィールドを順次読み出します
                            Field = Format.Begin();

                            // 3F伝票処理時に2F伝票を判定する 2013/07/01
                            if (FormatName == Properties.Settings.Default.instDir + Properties.Settings.Default.fmtHPath)
                            {
                                string fldText = string.Empty;
                                while (Field != null)
                                {
                                    // 指定フィールドを認識し、テキストを取得(対象は最終フィールド)
                                    fldText = Field.ExtractFieldText();

                                    // 次のフィールドの取得
                                    Field = Format.Next();
                                }

                                // 再度認識されたフィールドを順次読み出します 2013/07/01
                                Field = Format.Begin();

                                // 2F書式伝票のとき(指定フィールドが空白である)
                                if (fldText.Trim().Length == 0)
                                {
                                    // 2F伝票フォルダへ移動する
                                    System.IO.File.Move(files, path2Fdir + System.IO.Path.GetFileName(files));

                                    // ページをカウントして次の画像のOCR処理へ
                                    ocrPage++;
                                    nPage += 1;
                                    continue;
                                }
                            }

                            // 伝票フィールド編集
                            while (Field != null)
                            {
                                //カンマ付加
                                if (ocr_csv != string.Empty)
                                {
                                    ocr_csv += ",";
                                }

                                // 指定フィールドを認識し、テキストを取得
                                string strText = Field.ExtractFieldText();

                                // 年月日のとき各々独立フィールドに分解します
                                if (fIndex == 1)
                                {
                                    string strYYMMDD = strText.PadRight(6, '0');
                                    string ymd       = strYYMMDD.Substring(0, 2) + "," + strYYMMDD.Substring(2, 2) + "," + strYYMMDD.Substring(4, 2);
                                    ocr_csv += ymd;
                                }
                                else if (fIndex != 165)
                                {
                                    ocr_csv += strText;    // 他のフィールドで最終フィールド以外(2013/07/01)
                                }

                                // 摘要複写欄
                                if (fIndex == 10 || fIndex == 19 || fIndex == 28 || fIndex == 37 ||
                                    fIndex == 46 || fIndex == 55 || fIndex == 64 || fIndex == 73 || fIndex == 82 ||
                                    fIndex == 91 || fIndex == 100 || fIndex == 109 || fIndex == 118 || fIndex == 127 ||
                                    fIndex == 136 || fIndex == 145 || fIndex == 154 || fIndex == 163)
                                {
                                    ocr_csv += ",0";
                                }

                                // 改行
                                if (fIndex == 2 || fIndex == 11 || fIndex == 20 || fIndex == 29 || fIndex == 38 ||
                                    fIndex == 47 || fIndex == 56 || fIndex == 65 || fIndex == 74 || fIndex == 83 ||
                                    fIndex == 92 || fIndex == 101 || fIndex == 110 || fIndex == 119 || fIndex == 128 ||
                                    fIndex == 137 || fIndex == 146 || fIndex == 155)
                                {
                                    // ヘッダ業改行のとき明細行数を付加
                                    if (fIndex == 2)
                                    {
                                        ocr_csv += ",";
                                        ocr_csv += global.MAXGYOU_PRN.ToString();
                                    }

                                    ocr_csv += Environment.NewLine;

                                    // 取消欄
                                    ocr_csv += "0";
                                }

                                // 次のフィールドの取得
                                Field = Format.Next();
                                i    += 1;

                                // フィールドインデックスインクリメント
                                fIndex++;
                            }

                            //出力ファイル
                            System.IO.StreamWriter outFile = new System.IO.StreamWriter(InPath + System.IO.Path.GetFileNameWithoutExtension(files) + ".csv", false, System.Text.Encoding.GetEncoding(932));
                            outFile.WriteLine(ocr_csv);
                            outFile.Close();

                            //OCR変換枚数カウント
                            _okCount++;
                        }
                        catch (IDRWarning ex)
                        {
                            // Engine.MatchFormatRotate() で
                            // フォーマットにマッチしなかった場合、空ファイルを出力します
                            if (ex.No == ErrorCode.IDR_WARN_FORM_NO_MATCH)
                            {
                                //////// アンマッチフォルダへ移動する
                                //////System.IO.File.Move(files, NgPath + System.IO.Path.GetFileName(files));

                                // 区切り文字
                                ocr_csv = "*,";

                                // ファイルに画像ファイル名フィールドを付加します
                                ocr_csv += System.IO.Path.GetFileName(files);

                                // ヘッダ部 (決算仕訳区分、年、月、日、伝票№(NG))
                                ocr_csv += ",0,,,,NG," + global.MAXGYOU_PRN.ToString() + Environment.NewLine;

                                //// 明細部
                                string meisai = "0,,,,,,,,,0," + Environment.NewLine;
                                for (int i = 0; i < 18; i++)
                                {
                                    ocr_csv += meisai;
                                }

                                //出力ファイル
                                System.IO.StreamWriter outFile = new System.IO.StreamWriter(InPath + System.IO.Path.GetFileNameWithoutExtension(files) + ".csv", false, System.Text.Encoding.GetEncoding(932));
                                outFile.WriteLine(ocr_csv);
                                outFile.Close();

                                _ngCount++;  //NG枚数カウント
                            }
                        }

                        ocrPage++;
                        nPage += 1;
                    }
                }

                // いったんオーナーをアクティブにする
                this.Activate();

                // 進行状況ダイアログを閉じる
                frmP.Close();

                // オーナーのフォームを有効に戻す
                this.Enabled = true;

                // OCR変換画像とCSVデータをOCR結果出力フォルダへ移動する
                foreach (string files in System.IO.Directory.GetFiles(InPath, "*.*"))
                {
                    System.IO.File.Move(files, rePath + System.IO.Path.GetFileName(files));
                }

                // 終了メッセージ (2F伝票画像がなければ処理終了とみなす)
                var f2Tif = System.IO.Directory.GetFileSystemEntries(Properties.Settings.Default.instDir + global.DIR_2F, "*.tif");

                if (f2Tif.Length == 0)
                {
                    string        finMessage = string.Empty;
                    StringBuilder sb         = new StringBuilder();
                    sb.Append("OCR認識処理が終了しました。");
                    sb.Append("引き続き修正確認&受け渡しデータ作成を行ってください。");
                    sb.Append(Environment.NewLine);
                    sb.Append(Environment.NewLine);
                    sb.Append("OK件数 : ");
                    sb.Append(_okCount.ToString());
                    sb.Append(Environment.NewLine);
                    sb.Append("NG件数 : ");
                    sb.Append(_ngCount.ToString());
                    sb.Append(Environment.NewLine);

                    MessageBox.Show(sb.ToString(), "処理終了", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                FormatList.Delete(0);
            }
            catch (System.Exception ex)
            {
                // 例外のキャッチ
                string errMessage = string.Empty;
                errMessage += "System例外が発生しました:" + Environment.NewLine;
                errMessage += "必要なDLL等が実行モジュールと同ディレクトリに存在するか確認してください。:" + Environment.NewLine;
                errMessage += ex.Message.ToString();
                MessageBox.Show(errMessage, "エラー", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            finally
            {
                en.Release();
            }
        }
Пример #11
0
        /// <summary>
        /// Converts all the image file into one PDF file.
        /// </summary>
        /// <param name="imagePath">The collection of image files to combine.</param>
        /// <returns>True if the conversion was successful; else false.</returns>
        private bool ConvertImage(string[] imagePath)
        {
            try
            {
                // Get the unlock key
                RasterSupport.Unlock(RasterSupportType.PdfSave, _documentUnlockKey);

                // Startup the codecs
                RasterCodecs.Startup();
                using (RasterCodecs codecs = new RasterCodecs())
                {
                    // Assign the codec options
                    codecs.Options.Jpeg.Save.QualityFactor     = _pdfDocumentQualityFactor;
                    codecs.Options.Jpeg.Save.SaveWithStamp     = false;
                    codecs.Options.Jpeg.Save.StampBitsPerPixel = 0;

                    // Set the raster image format.
                    RasterImageFormat rasterImageFormat = RasterImageFormat.RasPdfJpeg411;

                    // Set the pdf save type.
                    switch (_saveType)
                    {
                    case PdfSaveType.PdfA:
                        codecs.Options.Pdf.Save.SavePdfA = true;
                        rasterImageFormat = RasterImageFormat.RasPdfJpeg;
                        break;

                    case PdfSaveType.Pdf14:
                        codecs.Options.Pdf.Save.SavePdfv14 = true;
                        rasterImageFormat = RasterImageFormat.RasPdfJpeg411;
                        break;

                    case PdfSaveType.Pdf15:
                        codecs.Options.Pdf.Save.SavePdfv15 = true;
                        rasterImageFormat = RasterImageFormat.RasPdfJpeg422;
                        break;
                    }

                    // If the load tool resource path has been specified.
                    if (!String.IsNullOrEmpty(_leadToolResPath))
                    {
                        codecs.Options.Pdf.InitialPath = _leadToolResPath + "Lib;" + _leadToolResPath + "Fonts;" + _leadToolResPath + "Resource";
                    }

                    // For each image file found append into the PDF document.
                    for (int i = 0; i < imagePath.Length; i++)
                    {
                        // Load the image file into the image type.
                        using (System.Drawing.Image srcImage = System.Drawing.Image.FromFile(imagePath[i]))
                            using (RasterImage image = new RasterImage(srcImage))
                            {
                                if (i > 0)
                                {
                                    // Append each image file to the PDF document.
                                    codecs.Save(image, _pdfDocumentPath, rasterImageFormat, _pdfDocumentBitPerPixel, 1, 1, 1, CodecsSavePageMode.Append);
                                }
                                else
                                {
                                    // Create or overwrite the PDF document and
                                    // place to first image at the top of the PDF.
                                    codecs.Save(image, _pdfDocumentPath, rasterImageFormat, _pdfDocumentBitPerPixel, 1, 1, 1, CodecsSavePageMode.Overwrite);
                                }
                            }
                    }
                }

                // Return the result.
                return(true);
            }
            finally
            {
                // Shutdown the codecs
                RasterCodecs.Shutdown();

                // If the event has been attached, then
                // send a complete to the client.
                if (OnComplete != null)
                {
                    OnComplete(this, new EventArgs());
                }
            }
        }
Пример #12
0
        /// <summary>
        /// Convert the current image to a PDF document.
        /// </summary>
        /// <returns>True if the conversion was successful; else false.</returns>
        private bool ConvertImage()
        {
            try
            {
                // Get the unlock key
                RasterSupport.Unlock(RasterSupportType.PdfSave, _documentUnlockKey);

                // Startup the codecs
                RasterCodecs.Startup();
                using (RasterCodecs codecs = new RasterCodecs())
                {
                    // Load the image file into the image type.
                    using (System.Drawing.Image srcImage = System.Drawing.Image.FromFile(_imageDocumentPath))
                        using (RasterImage image = new RasterImage(srcImage))
                        {
                            codecs.Options.Jpeg.Save.QualityFactor     = _pdfDocumentQualityFactor;
                            codecs.Options.Jpeg.Save.SaveWithStamp     = false;
                            codecs.Options.Jpeg.Save.StampBitsPerPixel = 0;
                            codecs.Options.Jpeg.Save.StampWidth        = image.Width;
                            codecs.Options.Jpeg.Save.StampHeight       = image.Height;

                            // Set the raster image format.
                            RasterImageFormat rasterImageFormat = RasterImageFormat.RasPdfJpeg411;

                            // Set the pdf save type.
                            switch (_saveType)
                            {
                            case PdfSaveType.PdfA:
                                codecs.Options.Pdf.Save.SavePdfA = true;
                                rasterImageFormat = RasterImageFormat.RasPdfJpeg;
                                break;

                            case PdfSaveType.Pdf14:
                                codecs.Options.Pdf.Save.SavePdfv14 = true;
                                rasterImageFormat = RasterImageFormat.RasPdfJpeg411;
                                break;

                            case PdfSaveType.Pdf15:
                                codecs.Options.Pdf.Save.SavePdfv15 = true;
                                rasterImageFormat = RasterImageFormat.RasPdfJpeg422;
                                break;
                            }

                            // If the load tool resource path has been specified.
                            if (!String.IsNullOrEmpty(_leadToolResPath))
                            {
                                codecs.Options.Pdf.InitialPath = _leadToolResPath + "Lib;" + _leadToolResPath + "Fonts;" + _leadToolResPath + "Resource";
                            }

                            // Attempt to save the image.
                            codecs.Save(image, _pdfDocumentPath, rasterImageFormat, _pdfDocumentBitPerPixel);
                        }
                }

                return(true);
            }
            finally
            {
                // Shutdown the codecs
                RasterCodecs.Shutdown();

                // If the event has been attached, then
                // send a complete to the client.
                if (OnComplete != null)
                {
                    OnComplete(this, new EventArgs());
                }
            }
        }
Пример #13
0
        ///------------------------------------------------------------------------------
        /// <summary>
        ///     マルチフレームの画像ファイルを頁ごとに分割する </summary>
        /// <param name="InPath">
        ///     画像ファイル入力パス</param>
        /// <param name="outPath">
        ///     分割後出力パス</param>
        /// <returns>
        ///     true:分割を実施, false:分割ファイルなし</returns>
        ///------------------------------------------------------------------------------
        private bool MultiTif(string InPath, string outPath, string fName)
        {
            //スキャン出力画像を確認
            if (System.IO.Directory.GetFiles(InPath, "*.tif").Count() == 0)
            {
                return(false);
            }

            // 出力先フォルダがなければ作成する
            if (System.IO.Directory.Exists(outPath) == false)
            {
                System.IO.Directory.CreateDirectory(outPath);
            }

            // 出力先フォルダ内の全てのファイルを削除する(通常ファイルは存在しないが例外処理などで残ってしまった場合に備えて念のため)
            foreach (string files in System.IO.Directory.GetFiles(outPath, "*"))
            {
                System.IO.File.Delete(files);
            }

            RasterCodecs.Startup();
            RasterCodecs cs = new RasterCodecs();

            int    _pageCount = 0;
            string fnm        = string.Empty;

            //コマンドを準備します。(傾き・ノイズ除去・リサイズ)
            DeskewCommand    Dcommand  = new DeskewCommand();
            DespeckleCommand Dkcommand = new DespeckleCommand();
            SizeCommand      Rcommand  = new SizeCommand();

            // マルチTIFを分解して画像ファイルをTRAYフォルダへ保存する
            foreach (string files in System.IO.Directory.GetFiles(InPath, "*.tif"))
            {
                // 画像読み出す
                RasterImage leadImg = cs.Load(files, 0, CodecsLoadByteOrder.BgrOrGray, 1, -1);

                // 頁数を取得
                int _fd_count = leadImg.PageCount;

                // 頁ごとに読み出す
                for (int i = 1; i <= _fd_count; i++)
                {
                    //ページを移動する
                    leadImg.Page = i;

                    // ファイル名設定
                    _pageCount++;
                    fnm = outPath + fName + string.Format("{0:000}", _pageCount) + ".tif";

                    // 2018/06/08 画像補正をしない
                    //画像補正処理 開始 ↓ ****************************
                    //try
                    //{
                    //    //画像の傾きを補正します。
                    //    Dcommand.Flags = DeskewCommandFlags.DeskewImage | DeskewCommandFlags.DoNotFillExposedArea;
                    //    Dcommand.Run(leadImg);
                    //}
                    //catch// (Exception e)
                    //{
                    //}                       //ノイズ除去

                    //try
                    //{
                    //    Dkcommand.Run(leadImg);
                    //}
                    //catch// (Exception e)
                    //{
                    //}

                    ////解像度調整(200*200dpi)
                    //leadImg.XResolution = 200;
                    //leadImg.YResolution = 200;

                    ////A4縦サイズに変換(ピクセル単位)
                    //Rcommand.Width = 1637;
                    //Rcommand.Height = 2322;
                    //try
                    //{
                    //    Rcommand.Run(leadImg);
                    //}
                    //catch// (Exception e)
                    //{
                    //}

                    //画像補正処理 終了↑ ****************************

                    // 画像保存
                    cs.Save(leadImg, fnm, RasterImageFormat.Tif, 0, i, i, 1, CodecsSavePageMode.Insert);
                }
            }

            //LEADTOOLS入出力ライブラリを終了します。
            RasterCodecs.Shutdown();

            // InPathフォルダの全てのtifファイルを削除する
            foreach (var files in System.IO.Directory.GetFiles(InPath, "*.tif"))
            {
                System.IO.File.Delete(files);
            }

            return(true);
        }
Пример #14
0
        private void imgResize(string files)
        {
            RasterCodecs.Startup();
            RasterCodecs cs = new RasterCodecs();

            int    _pageCount = 0;
            string fnm        = string.Empty;

            //コマンドを準備します。(傾き・ノイズ除去・リサイズ)
            DeskewCommand    Dcommand  = new DeskewCommand();
            DespeckleCommand Dkcommand = new DespeckleCommand();
            SizeCommand      Rcommand  = new SizeCommand();

            // 画像読み出す
            RasterImage leadImg = cs.Load(files, 0, CodecsLoadByteOrder.BgrOrGray, 1, -1);

            // 頁数を取得
            int _fd_count = leadImg.PageCount;

            //// ファイル名設定
            //_pageCount++;
            //fnm = outPath + fName + string.Format("{0:000}", _pageCount) + ".tif";
            fnm = files;

            //画像補正処理 開始 ↓ ****************************
            try
            {
                //画像の傾きを補正します。
                Dcommand.Flags = DeskewCommandFlags.DeskewImage | DeskewCommandFlags.DoNotFillExposedArea;
                Dcommand.Run(leadImg);
            }
            catch (Exception ex)
            {
                //MessageBox.Show(i + "画像の傾き補正エラー:" + ex.Message);
            }

            //ノイズ除去
            try
            {
                Dkcommand.Run(leadImg);
            }
            catch (Exception ex)
            {
                //MessageBox.Show(i + "ノイズ除去エラー:" + ex.Message);
            }

            //解像度調整(200*200dpi)
            leadImg.XResolution = 200;
            leadImg.YResolution = 200;

            //A4縦サイズに変換(ピクセル単位)
            Rcommand.Width  = 1637;
            Rcommand.Height = 2322;
            try
            {
                Rcommand.Run(leadImg);
            }
            catch (Exception ex)
            {
                //MessageBox.Show(i + "解像度調整エラー:" + ex.Message);
            }

            //画像補正処理 終了↑ ****************************

            // 画像保存
            //cs.Save(leadImg, fnm, RasterImageFormat.Tif, 1, 1, 1, 1, CodecsSavePageMode.Insert);
            cs.Save(leadImg, fnm, RasterImageFormat.Ccitt, 1, 1, 1, 1, CodecsSavePageMode.Insert);

            //LEADTOOLS入出力ライブラリを終了します。
            RasterCodecs.Shutdown();
        }
Пример #15
0
        private string DoTheConvert(string sourceImage, string actionProfile, string annotate, ReturnPath retPath)
        {
            string strRetFile = "";

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

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

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

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

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

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

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

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

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

            return(strRetFile);
        }
Пример #16
0
        private void Change_Click(object sender, EventArgs e)
        {
            // Some sanity checks !
            if (txtInFile.Text.Length == 0)
            {
                MessageBox.Show("Please enter a valid input file name ");
                return;
            }

            if (!System.IO.File.Exists(txtInFile.Text))
            {
                MessageBox.Show("Please enter a valid input file name ");
                return;
            }

            if (txtOutFile.Text.Length == 0)
            {
                MessageBox.Show("Please enter a valid output file name ");
                return;
            }
            if (txtInFile.Text == txtOutFile.Text)
            {
                MessageBox.Show("Input and output file names can't be the same!");
                return;
            }

            DicomDataSetSaveFlags saveFlags = (DicomDataSetSaveFlags.MetaHeaderPresent | DicomDataSetSaveFlags.GroupLengths);

            // Get desired transfer syntax
            string uid = ((MyTransferSyntax)cmbTransferSyntax.Items[cmbTransferSyntax.SelectedIndex]).szUID;
            int    nQFactor;

            if (IsUidUsingQFactor(uid))
            {
                nQFactor = Convert.ToInt16(txtQFactor.Text);
                if ((nQFactor < 2 || nQFactor > 255) && (nQFactor != 0))
                {
                    string message = "Please enter a valid quality factor:\r\n" +
                                     "\t 0 (lossless)\r\n" +
                                     "\t 2 (lossy highest quality) to 255 (lossy most compression)";

                    MessageBox.Show(message, "Please enter a valid quality factor.");
                    return;
                }
            }
            else
            {
                nQFactor = 0;
            }
            //Load input dataset

#if !(LEADTOOLS_V17_OR_LATER)
            RasterCodecs.Startup();
#endif
            DicomEngine.Startup();
            DicomDataSet DicomDs = new DicomDataSet();
            DicomDs.Reset();
            try
            {
                DicomDs.Load(txtInFile.Text, 0);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Failed to load the Dataset!");
                return;
            }

            if (IsUidJpeg2000(uid))
            {
                // Setting JPEG 2000 options
                DicomDs.Jpeg2000Options = m_J2KOptions;
            }

            // Ensure that the DICOM File Meta Information is added
            CheckFileMetaInfo(DicomDs);

            //Change dataset to desired transfer syntax
            try
            {
                ChangeTransferSyntaxFlags flags = ChangeTransferSyntaxFlags.None;
#if LEADTOOLS_V175_OR_LATER
                if (checkBoxYbrFull.Checked)
                {
                    flags |= ChangeTransferSyntaxFlags.YbrFull;
                }
#endif

#if LEADTOOLS_V19_OR_LATER
                DicomDs.ChangeTransferSyntax(txtOutFile.Text, uid, nQFactor, flags, saveFlags);
#else
                DicomDs.ChangeTransferSyntax(uid, nQFactor, flags);
#endif
            }
            catch (Exception ex)
            {
                string errorString = ex.Message.ToLower();
                if (errorString.Contains("parameter"))
                {
                    const string strErr = "Failed to change dataset transfer syntax.\nPossible cause:\" Bits Allocated\" for source dataset doesn't match desired \"Transfer Syntax\".";
                    MessageBox.Show(strErr, "Failed to change dataset transfer syntax.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    MessageBox.Show(ex.Message, "LEAD Error");
                }

                return;
            }

#if !LEADTOOLS_V19_OR_LATER
            // Save dataset!
            try
            {
                DicomDs.Save(txtOutFile.Text, saveFlags);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Failed to save dataset");
                return;
            }
#endif // #if !LEADTOOLS_V19_OR_LATER

            DicomEngine.Shutdown();

#if !LEADTOOLS_V17_OR_LATER
            RasterCodecs.Shutdown();
#endif
            MessageBox.Show("Conversion Succeeded", "SUCCESS");

            //this.Cursor = Cursors.WaitCursor;
            //this.Cursor = Cursors.Arrow;
        }