示例#1
0
        private static TextResult[] DecodeFile(string strImagePath, int mode, int iLeft, int iTop, int iRight, int iBottom)
        {
            BarcodeReader _br = new BarcodeReader();

            _br.LicenseKeys = "t0068MgAAAJbpvFwUvsodF81FjWojDo91ZYmDf3+aNdOGPOBOygS6Yte0JFqPMt/DnNMdfGS4gInUd+5RYOCX6IramuO+m4A=";
            string[] strTemplateNameArray       = { "All_DEFAULT", "All_DEFAULT_WITHREGION" };
            string   tempDefaultTemplateJson    = "{\"Version\": \"2.0\",\"ImageParameter\": {\"Name\": \"" + strTemplateNameArray[0] + "\",\"BarcodeFormatIds\": [\"All\"],\"RegionPredetectionMode\": \"Enable\"}}";
            string   tempTemplateJsonWithRegion = "{\"Version\": \"2.0\",\"ImageParameter\": {\"Name\": \"" + strTemplateNameArray[1] + "\",\"BarcodeFormatIds\": [\"All\"],\"RegionPredetectionMode\": \"Disable\",\"RegionDefinitionNameArray\": [\"Region\"]},\"RegionDefinitionArray\": [{\"Name\": \"Region\",\"MeasuredByPercentage\": true" + ",\"Left\":" + iLeft.ToString() + ",\"Top\":" + iTop.ToString() + ",\"Right\":" + iRight.ToString() + ",\"Bottom\":" + iBottom.ToString() + "}]}";

            if (mode == 0)
            {
                // load template json as a string.
                string        errorstring   = "";
                EnumErrorCode temperrorcode = _br.InitRuntimeSettingsWithString(tempDefaultTemplateJson, EnumConflictMode.ECM_Overwrite, out errorstring);
            }
            else
            {
                // load template json as a string.
                string        errorstring   = "";
                EnumErrorCode temperrorcode = _br.InitRuntimeSettingsWithString(tempTemplateJsonWithRegion, EnumConflictMode.ECM_Overwrite, out errorstring);
            }
            _br.DecodeFile(strImagePath, strTemplateNameArray[mode]);
            TextResult[] result = _br.DecodeFile(strImagePath, strTemplateNameArray[mode]);

            return(result);
        }
        private static TextResult[] DecodeFile(string strImagePath, int mode, int iLeft, int iTop, int iRight, int iBottom)
        {
            BarcodeReader _br = new BarcodeReader();

            _br.ProductKeys = "t0068MgAAADaH8yokXmKf3axcV99lMBDDRYEZIsBZ5PPiekmW820HqSR2tQ/VOjuXPvq1FCvla7eS6KmEMUFgHZR9X7GuR2s=";
            string[] strTemplateNameArray       = { "All_DEFAULT", "All_DEFAULT_WITHREGION" };
            string   tempDefaultTemplateJson    = "{\"Version\": \"2.0\",\"ImageParameter\": {\"Name\": \"" + strTemplateNameArray[0] + "\",\"BarcodeFormatIds\": [\"BF_ALL\"],\"RegionPredetectionModes\": [{\"Mode\":\"RPM_GENERAL_RGB_CONTRAST\"}]}}";
            string   tempTemplateJsonWithRegion = "{\"Version\": \"2.0\",\"ImageParameter\": {\"Name\": \"" + strTemplateNameArray[1] + "\",\"BarcodeFormatIds\": [\"BF_ALL\"],\"RegionPredetectionModes\": [{\"Mode\":\"RPM_GENERAL\"}],\"RegionDefinitionNameArray\": [\"Region\"]},\"RegionDefinitionArray\": [{\"Name\": \"Region\",\"MeasuredByPercentage\": 1" + ",\"Left\":" + iLeft.ToString() + ",\"Top\":" + iTop.ToString() + ",\"Right\":" + iRight.ToString() + ",\"Bottom\":" + iBottom.ToString() + "}]}";

            if (mode == 0)
            {
                // load template json as a string.
                string        errorstring   = "";
                EnumErrorCode temperrorcode = _br.InitRuntimeSettingsWithString(tempDefaultTemplateJson, EnumConflictMode.CM_OVERWRITE, out errorstring);
            }
            else
            {
                // load template json as a string.
                string        errorstring   = "";
                EnumErrorCode temperrorcode = _br.InitRuntimeSettingsWithString(tempTemplateJsonWithRegion, EnumConflictMode.CM_OVERWRITE, out errorstring);
            }
            _br.DecodeFile(strImagePath, strTemplateNameArray[mode]);
            TextResult[] result = _br.DecodeFile(strImagePath, strTemplateNameArray[mode]);

            return(result);
        }
 public void DecodeFile(string file)
 {
     TextResult[] tempResult = mBarcodeRader.DecodeFile(file, "");
     if (tempResult != null && tempResult.Length > 0)
     {
         if (OnBarcodeRecognized != null)
         {
             OnBarcodeRecognized(tempResult);
         }
     }
 }
示例#4
0
        private static TextResult[] DecodeFile(BarcodeReader _br, string strImagePath)
        {
            //modifiy the default template and decode file.
            PublicRuntimeSettings settings = _br.GetRuntimeSettings();

            //set max barcode count.
            settings.mMaxBarcodesCount = 1;
            _br.UpdateRuntimeSettings(settings);
            TextResult[] result = _br.DecodeFile(strImagePath, "");
            return(result);
        }
示例#5
0
 private void ReadBarcodesButton_Click(object sender, EventArgs e)
 {
     Console.WriteLine("reading dbr");
     if (pictureBox1.Tag == null)
     {
         return;
     }
     if (DBRTemplateTextBox.Text != "")
     {
         try
         {
             String o = "";
             reader.InitRuntimeSettingsWithString(DBRTemplateTextBox.Text, EnumConflictMode.CM_OVERWRITE, errorMessage: out o);
             PublicRuntimeSettings rs = reader.GetRuntimeSettings();
             rs.ResultCoordinateType = EnumResultCoordinateType.RCT_PIXEL;
             reader.UpdateRuntimeSettings(rs);
         }
         catch (Exception)
         {
             throw;
         }
     }
     try
     {
         TextResult[] results    = reader.DecodeFile(pictureBox1.Tag.ToString(), "");
         string       outputInfo = "Total barcodes found: " + results.Length.ToString();
         Console.WriteLine(outputInfo);
         for (int iIndex = 0; iIndex < results.Length; ++iIndex)
         {
             int        iBarcodeIndex = iIndex + 1;
             string     builder       = "Barcode " + iBarcodeIndex.ToString() + ":\r\n";
             TextResult result        = results[iIndex];
             if (result.BarcodeFormat != 0)
             {
                 builder += "    Type: " + result.BarcodeFormatString + "\r\n";
             }
             else
             {
                 builder += "    Type: " + result.BarcodeFormatString_2 + "\r\n";
             }
             builder += "    Value: " + result.BarcodeText + "\r\n";
             draw(pictureBox1.Image, result.LocalizationResult.ResultPoints);
             Console.WriteLine(builder);
             textBox1.Text = textBox1.Text + builder;
         }
         textBox1.Tag = results;
     }
     catch (BarcodeReaderException exp)
     {
         Console.WriteLine(exp.Message);
         textBox1.Text = exp.Message;
     }
 }
示例#6
0
        private static TextResult[] DecodeFile(BarcodeReader _br, string strImagePath)
        {
            //modifiy the default template and decode file.
            PublicParameterSettings settings = _br.GetTemplateSettings("");

            //set excepted barcode count.
            settings.mExpectedBarcodesCount  = 0x7ffffff;
            settings.mRegionPredetectionMode = RegionPredetectionMode.RPM_Enable;
            _br.SetTemplateSettings(settings);
            TextResult[] result = _br.DecodeFile(strImagePath, "");
            return(result);
        }
        private static TextResult[] DecodeFile(string strImagePath, int mode, int iLeft, int iTop, int iRight, int iBottom)
        {
            BarcodeReader _br = new BarcodeReader();

            _br.LicenseKeys = "t0068MgAAAEBDbYNoTMuh5/ccI24YdlzcggFG93NGuHrF/AWmcbKAsObdABAWC5GvZZpXBlfrsJhkQ1yMO4B8qTUnk6S8HdY=.";
            string[] strTemplateNameArray       = { "All_DEFAULT", "All_DEFAULT_WITHREGION" };
            string   tempDefaultTemplateJson    = "{\"Version\": \"1.0\",\"ImageParameters\": {\"Name\": \"" + strTemplateNameArray[0] + "\",\"BarcodeFormatIds\": [\"All\"],\"RegionPredetectionMode\": \"Enable\"}}";
            string   tempTemplateJsonWithRegion = "{\"ImageParameters\": {\"Name\": \"" + strTemplateNameArray[1] + "\",\"BarcodeFormatIds\": [\"All\"],\"RegionPredetectionMode\": \"Disable\",\"RegionDefinitionNameArray\": [\"Region\"]},\"RegionDefinitionArray\": [{\"Name\": \"Region\",\"MeasuredByPercentage\": true" + ",\"Left\":" + iLeft.ToString() + ",\"Top\":" + iTop.ToString() + ",\"Right\":" + iRight.ToString() + ",\"Bottom\":" + iBottom.ToString() + "}]}";

            if (mode == 0)
            {
                // load template json as a string.
                _br.AppendParameterTemplate(tempDefaultTemplateJson);
            }
            else
            {
                // load template json as a string.
                _br.AppendParameterTemplate(tempTemplateJsonWithRegion);
            }
            _br.DecodeFile(strImagePath, strTemplateNameArray[mode]);
            TextResult[] result = _br.DecodeFile(strImagePath, strTemplateNameArray[mode]);

            return(result);
        }
示例#8
0
        protected void ReadBarcode(string imagePath)
        {
            BarcodeReader reader = new BarcodeReader(ConfigurationManager.AppSettings["BarcodeScannerAPIKey"]);

            TextResult[] result = reader.DecodeFile(imagePath, "");

            if (result.Length > 0)
            {
                lblResult.Text = "Number of barcodes found in image: " + result.Length;

                CreateResultsTable(result);
            }
            else
            {
                lblResult.Text = "No barcodes found in image";
            }
        }
示例#9
0
        private static TextResult[] DecodeFile(BarcodeReader _br, string strImagePath)
        {
            string strErrorMSG = "";

            //Best coverage settings
            _br.InitRuntimeSettingsWithString("{\"ImageParameter\":{\"Name\":\"BestCoverage\",\"DeblurLevel\":9,\"ExpectedBarcodesCount\":512,\"ScaleDownThreshold\":100000,\"LocalizationModes\":[{\"Mode\":\"LM_CONNECTED_BLOCKS\"},{\"Mode\":\"LM_SCAN_DIRECTLY\"},{\"Mode\":\"LM_STATISTICS\"},{\"Mode\":\"LM_LINES\"},{\"Mode\":\"LM_STATISTICS_MARKS\"}],\"GrayscaleTransformationModes\":[{\"Mode\":\"GTM_ORIGINAL\"},{\"Mode\":\"GTM_INVERTED\"}]}}", EnumConflictMode.CM_OVERWRITE, out strErrorMSG);
            //Best speed settings
            //_br.InitRuntimeSettingsWithString("{\"ImageParameter\":{\"Name\":\"BestSpeed\",\"DeblurLevel\":3,\"ExpectedBarcodesCount\":512,\"LocalizationModes\":[{\"Mode\":\"LM_SCAN_DIRECTLY\"}],\"TextFilterModes\":[{\"MinImageDimension\":262144,\"Mode\":\"TFM_GENERAL_CONTOUR\"}]}}", EnumConflictMode.CM_OVERWRITE, out strErrorMSG);
            //Balance settings
            //_br.InitRuntimeSettingsWithString("{\"ImageParameter\":{\"Name\":\"Balance\",\"DeblurLevel\":5,\"ExpectedBarcodesCount\":512,\"LocalizationModes\":[{\"Mode\":\"LM_CONNECTED_BLOCKS\"},{\"Mode\":\"LM_STATISTICS\"}]}}", EnumConflictMode.CM_OVERWRITE, out strErrorMSG);
            //modifiy the default template and decode file.
            PublicRuntimeSettings settings = _br.GetRuntimeSettings();

            //set excepted barcode count.
            settings.ExpectedBarcodesCount = 0x7ffffff;
            _br.UpdateRuntimeSettings(settings);
            TextResult[] result = _br.DecodeFile(strImagePath, "");
            return(result);
        }
示例#10
0
        public void DecodeFile(string file)
        {
            string strErrorMSG = "";

            //Best coverage settings
            mBarcodeRader.InitRuntimeSettingsWithString("{\"ImageParameter\":{\"Name\":\"BestCoverage\",\"DeblurLevel\":9,\"ExpectedBarcodesCount\":512,\"ScaleDownThreshold\":100000,\"LocalizationModes\":[{\"Mode\":\"LM_CONNECTED_BLOCKS\"},{\"Mode\":\"LM_SCAN_DIRECTLY\"},{\"Mode\":\"LM_STATISTICS\"},{\"Mode\":\"LM_LINES\"},{\"Mode\":\"LM_STATISTICS_MARKS\"}],\"GrayscaleTransformationModes\":[{\"Mode\":\"GTM_ORIGINAL\"},{\"Mode\":\"GTM_INVERTED\"}]}}", EnumConflictMode.CM_OVERWRITE, out strErrorMSG);
            //Best speed settings
            //mBarcodeRader.InitRuntimeSettingsWithString("{\"ImageParameter\":{\"Name\":\"BestSpeed\",\"DeblurLevel\":3,\"ExpectedBarcodesCount\":512,\"LocalizationModes\":[{\"Mode\":\"LM_SCAN_DIRECTLY\"}],\"TextFilterModes\":[{\"MinImageDimension\":262144,\"Mode\":\"TFM_GENERAL_CONTOUR\"}]}}", EnumConflictMode.CM_OVERWRITE, out strErrorMSG);
            //Balance settings
            //mBarcodeRader.InitRuntimeSettingsWithString("{\"ImageParameter\":{\"Name\":\"Balance\",\"DeblurLevel\":5,\"ExpectedBarcodesCount\":512,\"LocalizationModes\":[{\"Mode\":\"LM_CONNECTED_BLOCKS\"},{\"Mode\":\"LM_STATISTICS\"}]}}", EnumConflictMode.CM_OVERWRITE, out strErrorMSG);


            TextResult[] tempResult = mBarcodeRader.DecodeFile(file, "");
            if (tempResult != null && tempResult.Length > 0)
            {
                if (OnBarcodeRecognized != null)
                {
                    OnBarcodeRecognized(tempResult);
                }
            }
        }
示例#11
0
        private static TextResult[] DecodeFile(string strImagePath, int mode, int iLeft, int iTop, int iRight, int iBottom)
        {
            BarcodeReader _br = new BarcodeReader();

            _br.ProductKeys = "t0068MgAAAEUWFzAvIFjWdsOhURov3SljTtFakKFsHemq+2NKnvb5tEihIDmWlZsFpCWpVOnWr1Uw1NzIQ2EcnLj9Hxxvjfs=";

            string strErrorMSG = "";

            //Best coverage settings
            _br.InitRuntimeSettingsWithString("{\"ImageParameter\":{\"Name\":\"BestCoverage\",\"DeblurLevel\":9,\"ExpectedBarcodesCount\":512,\"ScaleDownThreshold\":100000,\"LocalizationModes\":[{\"Mode\":\"LM_CONNECTED_BLOCKS\"},{\"Mode\":\"LM_SCAN_DIRECTLY\"},{\"Mode\":\"LM_STATISTICS\"},{\"Mode\":\"LM_LINES\"},{\"Mode\":\"LM_STATISTICS_MARKS\"}],\"GrayscaleTransformationModes\":[{\"Mode\":\"GTM_ORIGINAL\"},{\"Mode\":\"GTM_INVERTED\"}]}}", EnumConflictMode.CM_OVERWRITE, out strErrorMSG);
            //Best speed settings
            //_br.InitRuntimeSettingsWithString("{\"ImageParameter\":{\"Name\":\"BestSpeed\",\"DeblurLevel\":3,\"ExpectedBarcodesCount\":512,\"LocalizationModes\":[{\"Mode\":\"LM_SCAN_DIRECTLY\"}],\"TextFilterModes\":[{\"MinImageDimension\":262144,\"Mode\":\"TFM_GENERAL_CONTOUR\"}]}}", EnumConflictMode.CM_OVERWRITE, out strErrorMSG);
            //Balance settings
            //_br.InitRuntimeSettingsWithString("{\"ImageParameter\":{\"Name\":\"Balance\",\"DeblurLevel\":5,\"ExpectedBarcodesCount\":512,\"LocalizationModes\":[{\"Mode\":\"LM_CONNECTED_BLOCKS\"},{\"Mode\":\"LM_STATISTICS\"}]}}", EnumConflictMode.CM_OVERWRITE, out strErrorMSG);


            string[] strTemplateNameArray       = { "All_DEFAULT", "All_DEFAULT_WITHREGION" };
            string   tempDefaultTemplateJson    = "{\"Version\": \"2.0\",\"ImageParameter\": {\"Name\": \"" + strTemplateNameArray[0] + "\",\"BarcodeFormatIds\": [\"BF_ALL\"],\"RegionPredetectionModes\": [{\"Mode\":\"RPM_GENERAL_RGB_CONTRAST\"}]}}";
            string   tempTemplateJsonWithRegion = "{\"Version\": \"2.0\",\"ImageParameter\": {\"Name\": \"" + strTemplateNameArray[1] + "\",\"BarcodeFormatIds\": [\"BF_ALL\"],\"RegionPredetectionModes\": [{\"Mode\":\"RPM_GENERAL\"}],\"RegionDefinitionNameArray\": [\"Region\"]},\"RegionDefinitionArray\": [{\"Name\": \"Region\",\"MeasuredByPercentage\": 1" + ",\"Left\":" + iLeft.ToString() + ",\"Top\":" + iTop.ToString() + ",\"Right\":" + iRight.ToString() + ",\"Bottom\":" + iBottom.ToString() + "}]}";

            if (mode == 0)
            {
                // load template json as a string.
                string        errorstring   = "";
                EnumErrorCode temperrorcode = _br.AppendTplStringToRuntimeSettings(tempDefaultTemplateJson, EnumConflictMode.CM_OVERWRITE, out errorstring);
            }
            else
            {
                // load template json as a string.
                string        errorstring   = "";
                EnumErrorCode temperrorcode = _br.AppendTplStringToRuntimeSettings(tempTemplateJsonWithRegion, EnumConflictMode.CM_OVERWRITE, out errorstring);
            }

            TextResult[] result = _br.DecodeFile(strImagePath, "");

            return(result);
        }
示例#12
0
        /// <summary>
        /// Using barcode value to split multi-page documents.
        /// </summary>
        /// <param name="strInputFolder">the path of folder that documents in</param>
        /// <param name="strOutputFolder">the path of folder that splitted documents saved in</param>
        private void DoSplit(string strInputFolder, string strOutputFolder)
        {
            int      iFileCount = 0;
            int      iSuccCount = 0;
            DateTime dtStart    = DateTime.Now;

            string[] files = Directory.GetFiles(strInputFolder);
            if (files != null)
            {
                foreach (string strFile in files)
                {
                    if (IsImageFile(strFile))
                    {
                        try
                        {
                            iFileCount++;
                            int    iDirectSeparator = strFile.LastIndexOf(Path.DirectorySeparatorChar);
                            string strFileName      = strFile.Substring(iDirectSeparator + 1);
                            tbLog.AppendText(string.Format("\r\nProcessing file {0}\r\n", strFileName));
                            if (!strFileName.EndsWith(".tiff", true, System.Globalization.CultureInfo.CurrentCulture) &&
                                !strFileName.EndsWith(".tif", true, System.Globalization.CultureInfo.CurrentCulture))
                            {
                                tbLog.AppendText("It's not a multi-page tiff file\r\n");
                                continue;
                            }

                            string[] Templates  = barcodeReader.GetAllParameterTemplateNames();
                            bool     bifcontian = false;
                            for (int i = 0; i < Templates.Length; i++)
                            {
                                if (format == Templates[i])
                                {
                                    bifcontian = true;
                                }
                            }
                            if (!bifcontian)
                            {
                                MessageBox.Show(("Failed to find the template named " + format + "."), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                            TextResult[] barcodes = barcodeReader.DecodeFile(strFile, format);
                            if (barcodes == null || barcodes.Length <= 0)
                            {
                                tbLog.AppendText("There is no barcode on the first page\r\n");
                            }
                            else
                            {
                                List <int>    separators        = new List <int>();
                                List <string> values            = new List <string>();
                                List <string> splittedFileNames = new List <string>();
                                foreach (TextResult result in barcodes)
                                {
                                    if (result.LocalizationResult.PageNumber >= 0)
                                    {
                                        if (!separators.Contains(result.LocalizationResult.PageNumber))
                                        {
                                            separators.Add(result.LocalizationResult.PageNumber);
                                            values.Add(result.BarcodeText);
                                        }
                                    }
                                }

                                string strOutputDir = null;
                                if (strOutputFolder.EndsWith(Path.DirectorySeparatorChar.ToString()))
                                {
                                    strOutputDir = strOutputFolder;
                                }
                                else
                                {
                                    strOutputDir = strOutputFolder + Path.DirectorySeparatorChar;
                                }

                                Image          img         = Image.FromFile(strFile);
                                int            iFrameCount = 1;
                                FrameDimension dimension   = FrameDimension.Page;
                                if (img.FrameDimensionsList != null && img.FrameDimensionsList.Length > 0)
                                {
                                    dimension   = new FrameDimension(img.FrameDimensionsList[0]);
                                    iFrameCount = img.GetFrameCount(dimension);
                                }
                                if (iFrameCount <= 1)
                                {
                                    tbLog.AppendText("It's not a multi-page tiff file\r\n");
                                    continue;
                                }

                                bool bHaveExistFile = false;

                                for (int i = 1; i <= separators.Count; i++)
                                {
                                    int start = separators[i - 1];
                                    int end   = start;
                                    if (i != separators.Count)
                                    {
                                        end = separators[i];
                                    }
                                    else
                                    {
                                        end = iFrameCount;
                                    }

                                    tbLog.AppendText(string.Format("Page: {0}\r\n", separators[i - 1]));
                                    tbLog.AppendText(string.Format("Barcode Value: {0}\r\n", values[i - 1]));

                                    string strOutputFileName = values[i - 1] + ".tiff";
                                    string strOutputFile     = strOutputDir + strOutputFileName;

                                    if (File.Exists(strOutputFile))
                                    {
                                        bHaveExistFile = true;
                                        tbLog.AppendText(string.Format("{0} exists,skip splitting pages({1}-{2}) in {3}\r\n", strOutputFileName, start + 1, end, strFileName));
                                        continue;
                                    }

                                    ImageCodecInfo   tiffCodeInfo = null;
                                    ImageCodecInfo[] codeinfos    = ImageCodecInfo.GetImageDecoders();
                                    foreach (ImageCodecInfo codeinfo in codeinfos)
                                    {
                                        if (codeinfo.FormatID == ImageFormat.Tiff.Guid)
                                        {
                                            tiffCodeInfo = codeinfo;
                                            break;
                                        }
                                    }

                                    System.Drawing.Imaging.EncoderParameters encoderParams = null;
                                    if (end - start == 1)
                                    {
                                        encoderParams          = new System.Drawing.Imaging.EncoderParameters(1);
                                        encoderParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)System.Drawing.Imaging.EncoderValue.CompressionLZW);
                                    }
                                    else
                                    {
                                        encoderParams          = new System.Drawing.Imaging.EncoderParameters(2);
                                        encoderParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)System.Drawing.Imaging.EncoderValue.CompressionLZW);
                                        encoderParams.Param[1] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)System.Drawing.Imaging.EncoderValue.MultiFrame);
                                    }

                                    img.SelectActiveFrame(dimension, start);
                                    img.Save(strOutputFile, tiffCodeInfo, encoderParams);
                                    start++;
                                    if (start < end)
                                    {
                                        encoderParams.Param[1] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)System.Drawing.Imaging.EncoderValue.FrameDimensionPage);
                                        for (int k = start; k < end; k++)
                                        {
                                            img.SelectActiveFrame(dimension, k);
                                            img.SaveAdd(img, encoderParams);
                                        }
                                    }
                                    splittedFileNames.Add(strOutputFileName);
                                }

                                img.Dispose();
                                if (!bHaveExistFile)
                                {
                                    iSuccCount++;
                                }

                                string strFiles = null;
                                if (splittedFileNames.Count > 0)
                                {
                                    strFiles = splittedFileNames[0];
                                    for (int j = 1; j < splittedFileNames.Count; j++)
                                    {
                                        strFiles += "," + splittedFileNames[j];
                                    }
                                }
                                if (strFiles != null)
                                {
                                    tbLog.AppendText(string.Format("Splitted it to multiple files:{0}\r\n", strFiles));
                                }
                            }
                        }
                        catch (Exception exp)
                        {
                            tbLog.AppendText(exp.Message + "\r\n");
                        }
                        tbLog.Refresh();
                    }
                }
            }

            tbLog.AppendText("Completed\r\n");
            tbLog.AppendText(string.Format("Files Total: {0} file(s), Success: {1} file(s)\r\n", iFileCount, iSuccCount));
            tbLog.AppendText(string.Format("Total cost time: {0}ms", (int)(DateTime.Now - dtStart).TotalMilliseconds));
        }
示例#13
0
        /// <summary>
        /// Using barcode value to split multi-page documents.
        /// </summary>
        /// <param name="strInputFolder">the path of folder that documents in</param>
        /// <param name="strOutputFolder">the path of folder that splitted documents saved in</param>
        private void DoSplit(string strInputFolder, string strOutputFolder)
        {
            int      iFileCount = 0;
            int      iSuccCount = 0;
            DateTime dtStart    = DateTime.Now;

            string[] files = Directory.GetFiles(strInputFolder);
            if (files != null)
            {
                foreach (string strFile in files)
                {
                    if (IsImageFile(strFile))
                    {
                        try
                        {
                            iFileCount++;
                            int    iDirectSeparator = strFile.LastIndexOf(Path.DirectorySeparatorChar);
                            string strFileName      = strFile.Substring(iDirectSeparator + 1);
                            tbLog.AppendText(string.Format("\r\nProcessing file {0}\r\n", strFileName));
                            if (!strFileName.EndsWith(".tiff", true, System.Globalization.CultureInfo.CurrentCulture) &&
                                !strFileName.EndsWith(".tif", true, System.Globalization.CultureInfo.CurrentCulture))
                            {
                                tbLog.AppendText("It's not a multi-page tiff file\r\n");
                                continue;
                            }

                            string[] Templates  = barcodeReader.GetAllParameterTemplateNames();
                            bool     bifcontian = false;

                            string strErrorMSG = "";
                            //Best coverage settings
                            barcodeReader.InitRuntimeSettingsWithString("{\"ImageParameter\":{\"Name\":\"BestCoverage\",\"DeblurLevel\":9,\"ExpectedBarcodesCount\":512,\"ScaleDownThreshold\":100000,\"LocalizationModes\":[{\"Mode\":\"LM_CONNECTED_BLOCKS\"},{\"Mode\":\"LM_SCAN_DIRECTLY\"},{\"Mode\":\"LM_STATISTICS\"},{\"Mode\":\"LM_LINES\"},{\"Mode\":\"LM_STATISTICS_MARKS\"}],\"GrayscaleTransformationModes\":[{\"Mode\":\"GTM_ORIGINAL\"},{\"Mode\":\"GTM_INVERTED\"}]}}", EnumConflictMode.CM_OVERWRITE, out strErrorMSG);
                            //Best speed settings
                            //barcodeReader.InitRuntimeSettingsWithString("{\"ImageParameter\":{\"Name\":\"BestSpeed\",\"DeblurLevel\":3,\"ExpectedBarcodesCount\":512,\"LocalizationModes\":[{\"Mode\":\"LM_SCAN_DIRECTLY\"}],\"TextFilterModes\":[{\"MinImageDimension\":262144,\"Mode\":\"TFM_GENERAL_CONTOUR\"}]}}", EnumConflictMode.CM_OVERWRITE, out strErrorMSG);
                            //Balance settings
                            //barcodeReader.InitRuntimeSettingsWithString("{\"ImageParameter\":{\"Name\":\"Balance\",\"DeblurLevel\":5,\"ExpectedBarcodesCount\":512,\"LocalizationModes\":[{\"Mode\":\"LM_CONNECTED_BLOCKS\"},{\"Mode\":\"LM_STATISTICS\"}]}}", EnumConflictMode.CM_OVERWRITE, out strErrorMSG);

                            PublicRuntimeSettings tempParameterSettings = barcodeReader.GetRuntimeSettings();
                            tempParameterSettings.BarcodeFormatIds = formatid;
                            barcodeReader.UpdateRuntimeSettings(tempParameterSettings);

                            TextResult[] barcodes = barcodeReader.DecodeFile(strFile, "");
                            if (barcodes == null || barcodes.Length <= 0)
                            {
                                tbLog.AppendText("There is no barcode on the first page\r\n");
                            }
                            else
                            {
                                List <int>    separators        = new List <int>();
                                List <string> values            = new List <string>();
                                List <string> splittedFileNames = new List <string>();
                                foreach (TextResult result in barcodes)
                                {
                                    if (result.LocalizationResult.PageNumber >= 0)
                                    {
                                        if (!separators.Contains(result.LocalizationResult.PageNumber))
                                        {
                                            separators.Add(result.LocalizationResult.PageNumber);
                                            values.Add(result.BarcodeText);
                                        }
                                    }
                                }

                                string strOutputDir = null;
                                if (strOutputFolder.EndsWith(Path.DirectorySeparatorChar.ToString()))
                                {
                                    strOutputDir = strOutputFolder;
                                }
                                else
                                {
                                    strOutputDir = strOutputFolder + Path.DirectorySeparatorChar;
                                }

                                Image          img         = Image.FromFile(strFile);
                                int            iFrameCount = 1;
                                FrameDimension dimension   = FrameDimension.Page;
                                if (img.FrameDimensionsList != null && img.FrameDimensionsList.Length > 0)
                                {
                                    dimension   = new FrameDimension(img.FrameDimensionsList[0]);
                                    iFrameCount = img.GetFrameCount(dimension);
                                }
                                if (iFrameCount <= 1)
                                {
                                    tbLog.AppendText("It's not a multi-page tiff file\r\n");
                                    continue;
                                }

                                bool bHaveExistFile = false;

                                for (int i = 1; i <= separators.Count; i++)
                                {
                                    int start = separators[i - 1];
                                    int end   = start;
                                    if (i != separators.Count)
                                    {
                                        end = separators[i];
                                    }
                                    else
                                    {
                                        end = iFrameCount;
                                    }

                                    tbLog.AppendText(string.Format("Page: {0}\r\n", separators[i - 1]));
                                    tbLog.AppendText(string.Format("Barcode Value: {0}\r\n", values[i - 1]));

                                    string strOutputFileName = values[i - 1] + ".tiff";
                                    string strOutputFile     = strOutputDir + strOutputFileName;

                                    if (File.Exists(strOutputFile))
                                    {
                                        bHaveExistFile = true;
                                        tbLog.AppendText(string.Format("{0} exists,skip splitting pages({1}-{2}) in {3}\r\n", strOutputFileName, start + 1, end, strFileName));
                                        continue;
                                    }

                                    ImageCodecInfo   tiffCodeInfo = null;
                                    ImageCodecInfo[] codeinfos    = ImageCodecInfo.GetImageDecoders();
                                    foreach (ImageCodecInfo codeinfo in codeinfos)
                                    {
                                        if (codeinfo.FormatID == ImageFormat.Tiff.Guid)
                                        {
                                            tiffCodeInfo = codeinfo;
                                            break;
                                        }
                                    }

                                    System.Drawing.Imaging.EncoderParameters encoderParams = null;
                                    if (end - start == 1)
                                    {
                                        encoderParams          = new System.Drawing.Imaging.EncoderParameters(1);
                                        encoderParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)System.Drawing.Imaging.EncoderValue.CompressionLZW);
                                    }
                                    else
                                    {
                                        encoderParams          = new System.Drawing.Imaging.EncoderParameters(2);
                                        encoderParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)System.Drawing.Imaging.EncoderValue.CompressionLZW);
                                        encoderParams.Param[1] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)System.Drawing.Imaging.EncoderValue.MultiFrame);
                                    }

                                    img.SelectActiveFrame(dimension, start);
                                    img.Save(strOutputFile, tiffCodeInfo, encoderParams);
                                    start++;
                                    if (start < end)
                                    {
                                        encoderParams.Param[1] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)System.Drawing.Imaging.EncoderValue.FrameDimensionPage);
                                        for (int k = start; k < end; k++)
                                        {
                                            img.SelectActiveFrame(dimension, k);
                                            img.SaveAdd(img, encoderParams);
                                        }
                                    }
                                    splittedFileNames.Add(strOutputFileName);
                                }

                                img.Dispose();
                                if (!bHaveExistFile)
                                {
                                    iSuccCount++;
                                }

                                string strFiles = null;
                                if (splittedFileNames.Count > 0)
                                {
                                    strFiles = splittedFileNames[0];
                                    for (int j = 1; j < splittedFileNames.Count; j++)
                                    {
                                        strFiles += "," + splittedFileNames[j];
                                    }
                                }
                                if (strFiles != null)
                                {
                                    tbLog.AppendText(string.Format("Splitted it to multiple files:{0}\r\n", strFiles));
                                }
                            }
                        }
                        catch (Exception exp)
                        {
                            tbLog.AppendText(exp.Message + "\r\n");
                        }
                        tbLog.Refresh();
                    }
                }
            }

            tbLog.AppendText("Completed\r\n");
            tbLog.AppendText(string.Format("Files Total: {0} file(s), Success: {1} file(s)\r\n", iFileCount, iSuccCount));
            tbLog.AppendText(string.Format("Total cost time: {0}ms", (int)(DateTime.Now - dtStart).TotalMilliseconds));
        }