Tessnet2图片识别(2)

1. 引用 tessnet2.dll (只有NET2.0版本)

2. 视图页

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    主页
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2><%: ViewData["Message"] %></h2>
    <p>
        若要了解有关 ASP.NET MVC 的更多信息,请访问 <a href="http://asp.net/mvc" title="ASP.NET MVC 网站">http://asp.net/mvc</a></p>

<form id="form1" runat="server" enctype="multipart/form-data" action="indexnew" >
    <div>
    <a id="addAttach" href="#">添加上传文件</a>
    <div id="files">

    <input type="file" name="f1"/>

<%--    <input type="file" name="f2"/>--%>

    </div>
   <input type="submit" value="提交" />
    </div>
    </form>
</asp:Content>
View Code

3.后台代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using tessnet2;
using System.Drawing;
using System.Drawing.Imaging;
namespace MvcApplicationAndTesseert2.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult IndexNew()
        {
            HttpPostedFileBase hf = HttpContext.Request.Files[0];
            string path = Server.MapPath("~/image/"+DateTime.Now.ToString("yyyyMMddHHmmss")+".jpg");
            hf.SaveAs(path);

            //D:\CSharp\TessnetTest\ReCaptcha.jpg是待识别图片在电脑中的路径
            Bitmap map = new Bitmap(path);//@"D:\3.png"

            tessnet2.Tesseract ocr = new tessnet2.Tesseract();//声明一个OCR类   
            string txt = "";
            List<tessnet2.Word> result = new List<tessnet2.Word>();

            try
            {//当前识别变量设置:数字与大写字母,这种写法会导致无法识别小写字母,加上小写字母即可
                ocr.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
                //应用当前语言包。注,Tessnet2是支持多国语的。语言包下载链接:http://code.google.com/p/tesseract-ocr/downloads/list
                //D:\CSharp\TessnetTesttessdata是语言包在电脑中的路径
                ocr.Init(Server.MapPath("~/tessdata"), "eng", false);

                result = ocr.DoOCR(map, Rectangle.Empty);
                foreach (tessnet2.Word word in result)
                {
                    txt += word.Text;
                }
                Console.WriteLine(txt);
                Console.ReadLine();
            }
            catch (Exception ex)
            {

            }

         

            return Content(txt);
        }

        public ActionResult About()
        {
            return View();
        }
    }


      
}
View Code

 

 

demo

posted @ 2016-05-11 17:40  甜菜波波  阅读(370)  评论(0编辑  收藏  举报