Пример #1
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;

                            PublicRuntimeSettings tempParameterSettings = barcodeReader.GetRuntimeSettings();
                            tempParameterSettings.mBarcodeFormatIds = 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));
        }
Пример #2
0
        /// <summary>
        /// Using barcode value to rename documents.
        /// </summary>
        /// <param name="strInputFolder">the path of folder that documents in</param>
        /// <param name="strOutputFolder">the path of folder that renamed documents saved in</param>
        private void DoRename(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))
                    {
                        FileStream infs  = null;
                        FileStream outfs = null;
                        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));
                            Bitmap bmp = (Bitmap)Bitmap.FromFile(strFile);

                            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.DecodeBitmap(bmp, format);//DecodeFile(strFile);
                            bmp.Dispose();
                            if (barcodes == null || barcodes.Length <= 0)
                            {
                                tbLog.AppendText("There is no barcode on the first page\r\n");
                            }
                            else
                            {
                                tbLog.AppendText(string.Format("Page: {0}\r\n", barcodes[0].LocalizationResult.PageNumber));
                                tbLog.AppendText(string.Format("Barcode Value: {0}\r\n", barcodes[0].BarcodeText));

                                //output file name
                                int    iDot = strFileName.LastIndexOf('.');
                                string strOutputFileName = barcodes[0].BarcodeText + strFileName.Substring(iDot);
                                string strOutputFile     = null;
                                if (strOutputFolder.EndsWith(Path.DirectorySeparatorChar.ToString()))
                                {
                                    strOutputFile = strOutputFolder + strOutputFileName;
                                }
                                else
                                {
                                    strOutputFile = strOutputFolder + Path.DirectorySeparatorChar + strOutputFileName;
                                }
                                if (barcodes[0].BarcodeText.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
                                {
                                    tbLog.AppendText(string.Format("{0} contains character(s) that are not allowed in file names, skip renaming\r\n", barcodes[0].BarcodeText));
                                }
                                else
                                {
                                    if (File.Exists(strOutputFile))
                                    {
                                        tbLog.AppendText(string.Format("{0} exists, skip renaming {1}\r\n", strOutputFileName, strFileName));
                                    }
                                    else
                                    {
                                        infs  = new FileStream(strFile, FileMode.Open, FileAccess.Read);
                                        outfs = new FileStream(strOutputFile, FileMode.CreateNew);
                                        int    size   = 1 << 14;
                                        byte[] buffer = new byte[size];
                                        while (infs.Read(buffer, 0, size) > 0)
                                        {
                                            outfs.Write(buffer, 0, size);
                                        }
                                        infs.Close();
                                        outfs.Close();
                                        iSuccCount++;
                                        tbLog.AppendText(string.Format("Renamed to {0}\r\n", strOutputFileName));
                                    }
                                }
                            }
                        }
                        catch (Exception exp)
                        {
                            tbLog.AppendText(exp.Message + "\r\n");
                            if (infs != null)
                            {
                                infs.Close();
                            }
                            if (outfs != null)
                            {
                                outfs.Close();
                            }
                        }
                        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));
        }
Пример #3
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));
        }