示例#1
1
文件: Recognizer.cs 项目: bmwant/SSO
        public int Recognize(Bitmap bmpFile)
        {
            Bitmap bmpNew = new Bitmap(200, 200);
            Graphics gfx = Graphics.FromImage(bmpNew);
            gfx.FillRectangle(Brushes.White, 0, 0, 200, 200);
            gfx.DrawImage(bmpFile, 100, 100, bmpFile.Width, bmpFile.Height);
            string fileName = string.Format("{0}.tiff", number++);
            bmpNew.Save(fileName, System.Drawing.Imaging.ImageFormat.Tiff);
            MODI.Document md = new MODI.Document();
            try
            {
                md.Create(fileName);
                md.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
            }
            catch (Exception e)
            {
                //if cannot recognize there is must be empty image
                return 0;
            }

            MODI.Image image = (MODI.Image)md.Images[0];
            try
            {
                recognizedDigit = Int32.Parse(image.Layout.Text);
            }
            catch (Exception e)
            {
                return 0;
            }
            return recognizedDigit;
        }
示例#2
0
 private void GetWord()
 {
     if (File.Exists(requestImgFile))
     {
         MODI.Document doc = new MODI.Document();
     }
 }
        /// <summary>
        /// Check for Images
        /// read text from these images.
        /// save text from each image in text file automaticly.
        /// handle problems with images
        /// </summary>
        /// <param name="directoryPath">Set Directory Path to check for Images in it</param>
        public string doOCR(string file)
        {
            try
            {
                //OCR Operations ...
                MODI.Document md = new MODI.Document();
                md.Create(file);
                md.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
                MODI.Image image = (MODI.Image)md.Images[0];

                return(image.Layout.Text);
            }
            catch (Exception exc)
            {
                string msgTxt;
                if (exc.Message == "OCR running error")
                {
                    msgTxt = "Es konnten keine Buchstaben erkannt werden. \r\nDas Bild wird unter einer laufenden Nummer gespeichert.";
                }
                else
                {
                    msgTxt = exc.Message;
                }
                //uncomment the below code to see the expected errors
                System.Windows.MessageBox.Show(msgTxt, "OCR Exception");
                return(string.Empty);
            }
        }
示例#4
0
        private string ReadImage(string imagePath)
        {
            string imageText = string.Empty;
            try
            {
                // Grab Text From Image
                MODI.Document ModiObj = new MODI.Document();
                ModiObj.Create(imagePath);
                ModiObj.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);

                //Retrieve the text gathered from the image
                MODI.Image ModiImageObj = (MODI.Image)ModiObj.Images[0];

                //System.Console.WriteLine(ModiImageObj.Layout.Text);

                imageText = ModiImageObj.Layout.Text;

                ModiObj.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return imageText;
        }
示例#5
0
        /// <summary>
        ///  Read Text from Image and Store in Text File
        /// </summary>
        /// <param name="ImagePath">specify the Image Path</param>
        /// <param name="StoreTextFilePath">Specify the Store Text File</param>
        private static void ReadTextFromImage(String ImagePath, String StoreTextFilePath)
        {
            try
            {
                // Grab Text From Image
                MODI.Document ModiObj = new MODI.Document();
                ModiObj.Create(ImagePath);
                ModiObj.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);

                //Retrieve the text gathered from the image
                MODI.Image ModiImageObj = (MODI.Image)ModiObj.Images[0];

                // Store Image Content in Text File
                FileStream CreateFileObj = new FileStream(StoreTextFilePath, FileMode.Create);
                //save the image text in the text file
                StreamWriter WriteFileObj = new StreamWriter(CreateFileObj);
                WriteFileObj.Write(ModiImageObj.Layout.Text);
                WriteFileObj.Close();

                ModiObj.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
示例#6
0
        public string Analyse()
        {
            string texts = "";

            if (_MODIDocument == null)
            {
                return(texts);
            }
            try
            {
                // add event handler for progress visualisation
                //_MODIDocument.OnOCRProgress += new MODI._IDocumentEvents_OnOCRProgressEventHandler(this.ShowProgress);
                // the MODI call for OCR
                // _MODIDocument.OCR(_MODIParameters.Language,_MODIParameters.WithAutoRotation,_MODIParameters.WithStraightenImage);
                _MODIDocument.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
                //this.textBox1.Text = (_MODIDocument.Images[0] as MODI.Image).Layout.Text;
                //MessageBox.Show((_MODIDocument.Images[0] as MODI.Image).Layout.Text);
                texts = (_MODIDocument.Images[0] as MODI.Image).Layout.Text;
                //statusBar1.Text = "Ready.";
                _MODIDocument.Close(false);
                _MODIDocument = null;
            }
            catch (Exception ee)
            {
                // simple exception "handling"
                //MessageBox.Show(@""+ee.Message+@""+ee.ToString()+@"");
            }
            return(texts);
        }
示例#7
0
        /*
         * public SubtitleImage GetImage()
         * {
         *      Bitmap b = GetBitmap();
         *      Debugger.Print(Scan());
         *      return new SubtitleImage(GetBitmap());
         * }*/

        public string Scan()
        {
            string bitmapName = Path.GetTempPath() + "suprip_temp.png";

            MODI.Document md = new MODI.Document();
            GetBitmap().Save(bitmapName);

            md.Create(bitmapName);

            md.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);

            MODI.Image  image  = (MODI.Image)md.Images[0];
            MODI.Layout layout = image.Layout;

            string scanned = "";

            ocrWords = new List <OcrWord>();
            for (int j = 0; j < layout.Words.Count; j++)
            {
                // Get this word and deal with it.
                MODI.Word word = (MODI.Word)layout.Words[j];

                OcrWord w = new OcrWord(word.RecognitionConfidence, word.Text);
                ocrWords.Add(w);

                string text = word.Text;
                scanned += text + " ";
                int rc = word.RecognitionConfidence;
            }
            md.Close(false);

            return(scanned);
        }
示例#8
0
        private void pictureBox1_Click(object sender, EventArgs e)
        {
#if false
            MODI.Document doc = new MODI.Document();
            doc.Create(@"test.bmp");
            doc.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, false, false);

            StringBuilder str = new StringBuilder();

            for (int i = 0; i < doc.Images.Count; i++)
            {
                MODI.Image  img    = (MODI.Image)doc.Images[i];
                MODI.Layout layout = img.Layout;

                Console.WriteLine(layout.Text);
                Console.WriteLine();

                for (int j = 0; j < layout.Words.Count; j++)
                {
                    MODI.Word word = (MODI.Word)layout.Words[j];
                    str.Append("[" + word.Text + "]");
                }
            }
            StreamWriter outfile = new StreamWriter(@"ocr.txt");
            outfile.Write(str.ToString());
            outfile.Close();
#endif
        }
示例#9
0
        public int Recognize(Bitmap bmpFile)
        {
            Bitmap   bmpNew = new Bitmap(200, 200);
            Graphics gfx    = Graphics.FromImage(bmpNew);

            gfx.FillRectangle(Brushes.White, 0, 0, 200, 200);
            gfx.DrawImage(bmpFile, 100, 100, bmpFile.Width, bmpFile.Height);
            string fileName = string.Format("{0}.tiff", number++);

            bmpNew.Save(fileName, System.Drawing.Imaging.ImageFormat.Tiff);
            MODI.Document md = new MODI.Document();
            try
            {
                md.Create(fileName);
                md.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
            }
            catch (Exception e)
            {
                //if cannot recognize there is must be empty image
                return(0);
            }

            MODI.Image image = (MODI.Image)md.Images[0];
            try
            {
                recognizedDigit = Int32.Parse(image.Layout.Text);
            }
            catch (Exception e)
            {
                return(0);
            }
            return(recognizedDigit);
        }
示例#10
0
        // 点击“转换”事件
        private void button1_Click(object sender, EventArgs e)
        {
            StringBuilder sb       = new StringBuilder();
            string        img_Path = txt_imgpath.Text.Trim(); // 图片地址

            if (String.IsNullOrEmpty(img_Path))
            {
                MessageBox.Show("请先输入图片地址!");
                return;
            }
            try
            {
                MODI.Document doc = new MODI.Document();
                doc.Create(img_Path);
                MODI.Image  image;
                MODI.Layout layout;
                doc.OCR(GetLanuageType(cmb_languagetype.SelectedValue.ToString()), true, true);  // 识别文字类型
                for (int i = 0; i < doc.Images.Count; i++)
                {
                    image  = (MODI.Image)doc.Images[i];
                    layout = image.Layout;
                    sb.Append(layout.Text);
                }
                txt_result.Text = sb.ToString();
            }
            catch (Exception ex)
            {
                txt_result.Text = "转换失败!详情:" + ex.Message;
            }
        }
示例#11
0
 public override string OCR(string filename)
 {
     MODI.Document doc = new MODI.Document();
     doc.Create(filename);
     MODI.Image img = (MODI.Image)doc.Images[0];
     img.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
     var text = img.Layout.Text;
     doc.Close();
     return text;
 }
示例#12
0
        public string GetTextData(string path)
        {
            string fileExtension = Path.GetExtension(path);
            string fileName = Path.GetFileName(path);

            if (fileExtension != ".jpg" && fileExtension != ".JPG")
                throw new Exception("Nieobsługiwany typ pliku.");

            MODI.Document md = new MODI.Document();
            md.Create(path);
            md.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH);
            MODI.Image image = (MODI.Image)md.Images[0];

            return image.Layout.Text;
        }
示例#13
0
 /// <summary>
 /// Set the image..
 /// </summary>
 /// <param name="filename"></param>
 private void SetImage(string filename)
 {
     try
     {
         _MODIDocument = new MODI.Document();
         _MODIDocument.OnOCRProgress += new MODI._IDocumentEvents_OnOCRProgressEventHandler(this.ShowProgress);
         _MODIDocument.Create(filename);
         _Document             = null;
         axMiDocView1.Document = _MODIDocument;
         axMiDocView1.Refresh();
     }
     catch (System.Runtime.InteropServices.COMException ee)
     {
         MessageBox.Show(ee.Message);
     }
 }
示例#14
0
 private void SetImage(string filename)
 {
     // Bitmap nump = new Bitmap();
     // Bitmap myBitmap1 = new Bitmap(new fa;
     // set the image..
     try
     {
         _MODIDocument = new MODI.Document();
         _MODIDocument.Create(filename);
         //axMiDocView1.Document = _MODIDocument;
         //axMiDocView1.Refresh();
     }
     catch (System.Runtime.InteropServices.COMException ee)
     {
         MessageBox.Show(ee.Message);
     }
 }
 private string OCR(string fp)
 {
     try
     {
         //OCR Operations ...
         MODI.Document md = new MODI.Document();
         md.Create(fp);
         md.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
         MODI.Image image = (MODI.Image)md.Images[0];
         return(image.Layout.Text);
     }
     catch (Exception ex)
     {
         DebugHelper.WriteException(ex, "Error attempting to OCR " + fp);
         return(string.Empty);
     }
 }
 private string OCR(string fp)
 {
     try
     {
         //OCR Operations ...
         MODI.Document md = new MODI.Document();
         md.Create(fp);
         md.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
         MODI.Image image = (MODI.Image)md.Images[0];
         return image.Layout.Text;
     }
     catch (Exception ex)
     {
         DebugHelper.WriteException(ex, "Error attempting to OCR " + fp);
         return string.Empty;
     }
 }
示例#17
0
        private void button1_Click(object sender, EventArgs e)
        {
            MODI.Document doc = new MODI.Document();

            doc.Create("C:\\Users\\W_ang\\Pictures\\Camera Roll\\无标题.png");
            MODI.Image  image;
            MODI.Layout layout;
            doc.OCR(MODI.MiLANGUAGES.miLANG_CHINESE_SIMPLIFIED, true, true);
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < doc.Images.Count; i++)
            {
                image  = (MODI.Image)doc.Images[i];
                layout = image.Layout;
                sb.Append(layout.Text);
            }

            textBox1.Text = sb.ToString();
        }
示例#18
0
        public static Document CreateByMODI(MODI.Document document)
        {
            Document doc = new Document();

            for (int p = 0; p < document.Images.Count; p++)
            {
                Page page = new Page();
                doc.Pages.Add(page);
                MODI.Image image = (MODI.Image)document.Images[p];
                for (int i = 0; i < image.Layout.Words.Count; i++)
                {
                    MODI.Word MODIWord = (MODI.Word)image.Layout.Words[i];
                    Word      newWord  = Word.CreateBYMODI(MODIWord);

                    page.Words.Add(newWord);
                }
            }
            return(doc);
        }
示例#19
0
文件: Skype.cs 项目: JhetoX/SkypeOCR
        public static string getTextBitmap(string nameImage)
        {
            string text = null;
            try {
                string file = Path.GetFullPath(nameImage + ".jpg");
                MODI.Document md = new MODI.Document();
                md.Create(file);
                md.OCR(MODI.MiLANGUAGES.miLANG_SPANISH, false, false);
                MODI.Image image = (MODI.Image)md.Images[0];
                MODI.Layout layout = image.Layout;

                text = image.Layout.Text.Trim().Replace("\r\n", "");
                md.Close(false);

            }catch(Exception e){
                text = null;
            }
            return text;
        }
示例#20
0
        public static string getTextBitmap(string nameImage)
        {
            string text = null;

            try {
                string        file = Path.GetFullPath(nameImage + ".jpg");
                MODI.Document md   = new MODI.Document();
                md.Create(file);
                md.OCR(MODI.MiLANGUAGES.miLANG_SPANISH, false, false);
                MODI.Image  image  = (MODI.Image)md.Images[0];
                MODI.Layout layout = image.Layout;

                text = image.Layout.Text.Trim().Replace("\r\n", "");
                md.Close(false);
            }catch (Exception e) {
                text = null;
            }
            return(text);
        }
示例#21
0
        private static void ReadTextFromImage(String ImagePath)
        {
            try
            {
                // Grab Text From Image
                MODI.Document ModiObj = new MODI.Document();
                ModiObj.Create(ImagePath);
                ModiObj.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);

                //Retrieve the text gathered from the image
                MODI.Image ModiImageObj = (MODI.Image)ModiObj.Images[0];

                System.Console.WriteLine(ModiImageObj.Layout.Text);

                ModiObj.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
 /// <summary>
 /// office2007 MODI组件OCR识别
 /// </summary>
 /// <param name="imgPath"></param>
 /// <returns></returns>
 public string Ocr_2007(string imgPath)
 {
     try
     {
         var    imgType      = imgPath.Substring(imgPath.Length - 3);
         var    data         = File.ReadAllBytes(imgPath);
         string imgInfo      = "";
         int    i            = 0;
         var    localimgFile = AppDomain.CurrentDomain.BaseDirectory + @"\" + Guid.NewGuid().ToString() + "." + imgType;
         while (!imgInfo.Equals("转换成功") && i < 3)
         {
             ++i;
             imgInfo = this.GetBase64(data, imgType, localimgFile);
         }
         MODI.Document doc = new MODI.Document();
         doc.Create(localimgFile);
         MODI.Image  image;
         MODI.Layout layout;
         doc.OCR(MODI.MiLANGUAGES.miLANG_CHINESE_SIMPLIFIED, true, true);
         StringBuilder sb = new StringBuilder();
         image  = (MODI.Image)doc.Images[0];
         layout = image.Layout;
         sb.Append(layout.Text);
         doc = null;
         var localFilePath = AppDomain.CurrentDomain.BaseDirectory + @"\" + Guid.NewGuid().ToString() + ".txt";
         File.WriteAllText(localFilePath, sb.ToString());
         Console.WriteLine(sb.ToString());
         return(localFilePath);
     }
     catch (Exception e)
     {
         File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + @"\log.txt", e.ToString());
         return("");
     }
     finally
     {
         GC.Collect();
     }
 }
        private void pickConvertButton_Click(object sender, EventArgs e)
        {
            openFileDialog1.FileName = "";
            openFileDialog1.Filter   = "Image|*.jpg; *.png; *.bmp; *.jpeg; *.PNG;";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                pictureBox1.Image = Image.FromFile(openFileDialog1.FileName.ToString());
            }

            try
            {
                MODI.Document doc = new MODI.Document();
                doc.Create(openFileDialog1.FileName.ToString());

                if (comboBox1.SelectedIndex == 0)
                {
                    doc.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
                }
                else if (comboBox1.SelectedIndex == 1)
                {
                    doc.OCR(MODI.MiLANGUAGES.miLANG_GERMAN, true, true);
                }
                else
                {
                    doc.OCR(MODI.MiLANGUAGES.miLANG_TURKISH, true, true);
                }

                foreach (MODI.Image p in doc.Images)
                {
                    MODI.Layout txt = p.Layout;
                    richTextBox1.Text = txt.Text;
                }
                doc.Close();
            }
            catch (Exception errorMes)
            {
                MessageBox.Show(errorMes.Message.ToString(), "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
示例#24
0
        /// <summary>
        /// 识别率不是很高,微软的
        /// </summary>
        /// <param name="imgfileName"></param>
        /// <returns></returns>
        private string OcrFunc(string imgfileName) // 参数为包含文本的图片文件名
        {
            var langs = MODI.MiLANGUAGES.miLANG_ENGLISH;
            // MODI.MiLANGUAGES.miLANG_CHINESE_SIMPLIFIED; 中文含英文
            // MODI.MiLANGUAGES.miLANG_JAPANESE; 日文含英文

            var doc    = new MODI.Document();
            var image  = default(MODI.Image);
            var layout = default(MODI.Layout);

            try
            {
                doc.Create(imgfileName);
                doc.OCR(langs, true, true);
                var sb = new StringBuilder();

                for (int i = 0; i < doc.Images.Count; i++)
                {
                    image  = (MODI.Image)doc.Images[i];
                    layout = image.Layout;
                    sb.AppendLine(string.Format("{0}, {1}", i, layout.Text));
                }
                doc.Close(false);
                return(sb.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(string.Empty);
            }
            finally
            {
                layout = null;
                image  = null;
                doc    = null;
            }
        }
示例#25
0
        static void Main(string[] args)
        {
            MODI.Document doc = new MODI.Document();

            doc.Create("1.png");

            MODI.Image image;

            MODI.Layout layout;

            doc.OCR(MODI.MiLANGUAGES.miLANG_CHINESE_SIMPLIFIED, true, true);  // 识别简体中文
            string sb;

            for (int i = 0; i < doc.Images.Count; i++)

            {
                image = (MODI.Image)doc.Images[i];

                layout = image.Layout;

                Console.WriteLine(layout.Text);
            }
            Console.ReadLine();
        }
示例#26
0
        public void Convert(String inputFile, ConversionOptions options)
        {
            Object oMissing = Type.Missing;

            MODI.Document oMdiDoc = null;

            try
            {
                // Create an instance on a MODI document
                oMdiDoc = new MODI.Document();

                // Open the input file
                oMdiDoc.Create(inputFile);

                // For some unknown reason I need to do this otherwise pages 2+
                // will print tiny, shrunk pages in the top left corner, its either
                // this or calling SaveAs, this is quicker and easier...
                for (int i = 0; i < oMdiDoc.Images.Count; i++)
                {
                    var image = (MODI.Image)oMdiDoc.Images[i];
                    int tmp   = image.PixelHeight;
                    Marshal.ReleaseComObject(image);
                }

                using (var printSession = new TiffImagePrinter.PrintSession(options))
                {
                    try
                    {
                        oMdiDoc.PrintOut(0, -1, 1, printSession.PrinterName, "", false, MODI.MiPRINT_FITMODES.miPRINT_PAGE);
                    }
                    catch
                    {
                        printSession.Cancel();
                        throw;
                    }

                    // Wait for the jobs to start spooling to the printer
                    // TODO: make timeout parameterised
                    if (printSession.WaitForJobsSpooling())
                    {
                        // Now that its started spooling, wait for the job to complete
                        // Don't need to do this as MODI can be closed, this is to ensure the job
                        // completes successfully before returning control to the main thread
                        if (!printSession.WaitForJobsCompleted())
                        {
                            printSession.Cancel();
                            throw new TimeoutException("Timeout waiting for print job to complete.");
                        }
                    }
                    else
                    {
                        // The document did not enter the print queue so we need to cancel this
                        // printSession to allow the printer to return to the printer pool.
                        printSession.Cancel();

                        // Throw a TimeoutException
                        throw new TimeoutException("Timeout waiting for print job to spool.");
                    }
                }
            }
            finally
            {
                try
                {
                    if (oMdiDoc != null)
                    {
                        oMdiDoc.Close(false);
                        oMdiDoc = null;
                    }
                }
                catch
                {
                    // TODO: Log the error here...
                }
            }

            // Force a Garbage Collection
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
示例#27
0
        private string GetOCR(Bitmap big, Imaging.ImageRange range, bool flag = true)
        {
            Point p      = new Point();
            int   width  = 0;
            int   height = 0;

            p.X    = range.loc.X;
            p.Y    = range.loc.Y;
            width  = range.width;
            height = range.height;

            big = Imaging.CropImage(big, p, width, height);
            big = Imaging.ConvertFormat(big, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            //if (!flag)
            //big = Imaging.MakeGrayscale3(big);
            ////;
            //else
            //big = grayscale(big);

            //big.Save(Environment.CurrentDirectory + "\\test.png");
            ////tessnet2.Tesseract api = new tessnet2.Tesseract();

            ////api.Init()
            //OcrApi.PathToEngine = Environment.CurrentDirectory + @"\tesseract.dll";
            //OcrApi api = OcrApi.Create();
            //Languages[] lang = { Languages.English };
            //api.Init(lang, null, OcrEngineMode.OEM_TESSERACT_CUBE_COMBINED);
            //api.SetVariable("tessedit_char_whitelist", "0123456789");

            //string plainText = api.GetTextFromImage(big);
            //////Console.WriteLine(plainText);
            //////this.Invoke(new MethodInvoker(delegate() { txtLog.AppendText(plainText + Environment.NewLine); }));
            //api.Dispose();
            //api = null;
            //System.GC.Collect(0, GCCollectionMode.Forced);
            //System.GC.WaitForPendingFinalizers();

            //return plainText;
            var    tmpFile   = Path.GetTempFileName();
            string text      = "";
            var    bmp       = new Bitmap(Math.Max(big.Width, 1024), Math.Max(big.Height, 768));
            var    gfxResize = Graphics.FromImage(bmp);

            gfxResize.DrawImage(big, new Rectangle(0, 0, big.Width, big.Height));
            bmp.Save(tmpFile + ".png", ImageFormat.Png);

            //EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 100L); // 0(최저화질 고압축) ~ 100L(최고화질 저압축)
            //myEncoderParameters.Param[0] = myEncoderParameter;
            //bmp.Save(tmpFile + ".jpg", jpgEncoder, myEncoderParameters);

            var doc = new MODI.Document();

            doc.Create(tmpFile + ".png");

            //Regex reg = new Regex(@"[^\d]+");
            try
            {
                doc.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
                var img    = (MODI.Image)doc.Images[0];
                var layout = img.Layout;
                text = layout.Text;
                File.Delete(tmpFile);
                File.Delete(tmpFile + ".png");
            }
            catch (Exception e)
            {
                try
                {
                    doc.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, false, false);
                    var img    = (MODI.Image)doc.Images[0];
                    var layout = img.Layout;
                    text = layout.Text;
                }
                catch (Exception)
                {
                }
                finally
                {
                    File.Delete(tmpFile);
                    File.Delete(tmpFile + ".png");
                }
            }
            finally
            {
                File.Delete(tmpFile);
                File.Delete(tmpFile + ".png");
            }

            Int32 tryCheck = 0;

            text = Regex.Replace(text.Replace(" ", "").Replace(",", "").Replace(".", "").Trim(), @"[^\d]", "");
            Int32.TryParse(text, out tryCheck);
            if (tryCheck == 0 || tryCheck < 1000)
            {
                try
                {
                    EncoderParameters myEncoderParameters    = new EncoderParameters(1);
                    System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
                    ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);

                    tmpFile   = Path.GetTempFileName();
                    text      = "";
                    bmp       = new Bitmap(Math.Max(big.Width, 1024), Math.Max(big.Height, 768));
                    gfxResize = Graphics.FromImage(bmp);
                    gfxResize.DrawImage(big, new Rectangle(0, 0, big.Width, big.Height));

                    EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 100L);     // 0(최저화질 고압축) ~ 100L(최고화질 저압축)
                    myEncoderParameters.Param[0] = myEncoderParameter;
                    bmp.Save(tmpFile + ".jpg", jpgEncoder, myEncoderParameters);

                    doc = new MODI.Document();
                    doc.Create(tmpFile + ".jpg");
                    doc.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
                    var img    = (MODI.Image)doc.Images[0];
                    var layout = img.Layout;
                    text = layout.Text;
                }
                catch (Exception)
                {
                    doc.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, false, false);
                    var img    = (MODI.Image)doc.Images[0];
                    var layout = img.Layout;
                    text = layout.Text;
                }
                finally
                {
                    File.Delete(tmpFile);
                    File.Delete(tmpFile + ".jpg");
                }
            }

            text = Regex.Replace(text.Replace(" ", "").Replace(",", "").Replace(".", "").Trim(), @"[^\d]", "");
            doc.Close();
            doc = null;
            bmp.Dispose();
            bmp = null;
            System.GC.Collect(0, GCCollectionMode.Forced);
            System.GC.WaitForPendingFinalizers();
            return(text);
            //return "";
        }
示例#28
0
        // Save to MDI / TIFF
        private static void SaveToDoc(IList<int> pages, string modiFile, string outFile,
            MODI.MiFILE_FORMAT format, WaitForm wait, string tmpDir, bool closeForm=true)
        {
            MODI.Document modiDoc = null;

            try
            {
                wait.Status = "Saving to " + Path.GetFileName(outFile) + "...";
                modiDoc = new MODI.Document();
                modiDoc.Create(modiFile);

                // Can't find a way to add images to an empty doc...
                // doc.Images.Add doesn't like images from other docs
                // Probably the same bug that doesn't allow access to Image.Picture
                // This works backwards and removes unselected images from a complete doc
                for (int page = modiDoc.Images.Count - 1; page >= 0; page--)
                {
                    if (!pages.Contains(page))
                        modiDoc.Images.Remove(modiDoc.Images[page]);
                }

                modiDoc.SaveAs(outFile, format);
                //modiDoc.Close(false);
                // closing still keeps the file locked... see below
            }
            catch
            {
                wait.MessageSafe("Failed to save " + Path.GetFileName(outFile));
                if(closeForm)
                    wait.CloseSafe();
            }

            try
            {
                // The file gets locked for some reason until the program exits
                // or another save is made elsewhere
                // This unlocks the file on 2 of the 3 machines I tested on ...

                while (modiDoc.Images.Count > 1) // can't save w/ 0 imgs - leave 1
                    modiDoc.Images.Remove(modiDoc.Images[0]);

                // Needed new files for batch processing :/ This. Is. Ugly.
                // Not to mention slow

                if (!Directory.Exists(tmpDir))
                    Directory.CreateDirectory(tmpDir);
                modiDoc.SaveAs(tmpDir+"\\"+Path.GetRandomFileName());

               modiDoc.Close();

                if(closeForm)
                    wait.CloseSafe();
            }
            catch { }
        }
示例#29
0
        /*
        public SubtitleImage GetImage()
        {
            Bitmap b = GetBitmap();
            Debugger.Print(Scan());
            return new SubtitleImage(GetBitmap());
        }*/
        public string Scan()
        {
            string bitmapName = Path.GetTempPath() + "suprip_temp.png";
            MODI.Document md = new MODI.Document();
            GetBitmap().Save(bitmapName);

            md.Create(bitmapName);

            md.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);

            MODI.Image image = (MODI.Image)md.Images[0];
            MODI.Layout layout = image.Layout;

            string scanned = "";

            ocrWords = new List<OcrWord>();
            for (int j = 0; j < layout.Words.Count; j++)
            {
                // Get this word and deal with it.
                MODI.Word word = (MODI.Word)layout.Words[j];

                OcrWord w = new OcrWord(word.RecognitionConfidence, word.Text);
                ocrWords.Add(w);

                string text = word.Text;
                scanned += text + " ";
                int rc = word.RecognitionConfidence;
            }
            md.Close(false);

            return scanned;
        }
示例#30
0
        public bool Open(string file)
        {
            MODI.Document tmpDoc = new MODI.Document();

            try
            {
                tmpDoc.Create(file);
            }
            catch
            {
                return false;
            }

            if (tmpDoc.Images.Count > 0)
            {
                if (isOpen)
                    doc.Close();

                doc = tmpDoc;
                fileName = file;

                //converter.Document = doc;

                isOpen = true;
                //isOCRDone = false;
                isOCRDone = true;
                //lastFoundPage = -1;
                //lastFoundIndex = -1;
                lastSearch = "";
                lastBack = false;
                lastPage = doc.Images.Count;

                return true;
            }

            return false;
        }