
C# 中的 OCR CodeProject Tutorial:使用 IronOCR 從影像中萃取文字
在C#中進行光學字元識別(OCR)讓您可以從掃描文件、圖像檔案和TIFF文件中提取可機器讀取的文字,並在.NET應用程式中使用。 使用IronOCR,一個.NET原生的OCR程式庫,您只需安裝一個NuGet套件,然後通過幾行程式碼即可從圖像中讀取文字——沒有外部服務,沒有運行時依賴,也沒有按次API費用。
開始您的IronOCR免費試用以便遵循下述程式碼範例。
您如何在.NET項目中安裝IronOCR?
將OCR新增到.NET 10項目的最快方法是通過NuGet套件管理器。 在您的項目目錄中打開終端並運行.NET CLI命令,或使用Visual Studio中的套件管理器控制台:
安裝後,NuGet套件管理器會自動下載所有必需的程式集並建立引用。 IronOCR支持.NET Framework 4.6.2+、.NET Core 3.1+和.NET 5至.NET 10,所以它可用於控制臺應用程式、ASP.NET Core服務、WPF應用程式和Azure Functions。
您無需註冊授權碼即可在本地測試——在應用授權之前,輸出上會出現試用水印。 新增using指令,當您準備好生產時,在啟動時傳遞您的授權碼:
using IronOcr;
// Apply license key before any OCR calls (production only)
IronOcr.License.LicenseKey = "YOUR-LICENSE-KEY";Imports IronOcr
' Apply license key before any OCR calls (production only)
IronOcr.License.LicenseKey = "YOUR-LICENSE-KEY"查看IronOCR授權頁面以了解價格和激活詳情。
您如何從圖像文件中提取文字?
核心OCR工作流程涉及三個物件:OcrResult(輸出)。 下述範例會讀取一個PNG檔案並將識別的文字列印到控制台。
using IronOcr;
var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage("sample-document.png");
OcrResult result = ocr.Read(input);
Console.WriteLine(result.Text);Imports IronOcr
Dim ocr As New IronTesseract()
Using input As New OcrInput()
input.LoadImage("sample-document.png")
Dim result As OcrResult = ocr.Read(input)
Console.WriteLine(result.Text)
End Using光學字元識別輸出

IronTesseract將Tesseract 5引擎包裝成.NET友好的預設值,並進行自動模型管理。 OcrInput.LoadImage接受PNG、JPEG、BMP、GIF、TIFF和WebP文件,因此您很少需要在將圖像傳遞給引擎之前進行格式轉換。
OcrResult.Text屬性返回所有識別字元用新行連接起來的普通字串。 要獲得更豐富的存取--單詞邊界框、置信度得分、每段文字--導航result.Characters集合。
一些值得了解的關鍵屬性:
result.Pages[0].Text-- 單頁面的文字result.Words[n].Confidence-- 每個單詞的準確度(0.0 -- 1.0)result.Pages[0].Paragraphs-- 進行結構化提取的段落分割
您還可以呼叫ocr.ReadAsync(input)在桌面或網頁應用程式中保持UI執行緒空閒。
您如何處理掃描文件和TIFF文件?
多頁TIFF文件在文件掃描工作流中很常見。 IronOCR使用LoadImageFrames處理它們,允許您選擇具體要處理的幀(頁面)——這在您只需要一個大檔案的子集時非常有用。
using IronOcr;
var ocr = new IronTesseract();
using var input = new OcrInput();
int[] pageIndices = { 0, 1, 2 };
input.LoadImageFrames("scanned-documents.tiff", pageIndices);
// Correct skew and remove noise before reading
input.Deskew();
input.DeNoise();
OcrResult result = ocr.Read(input);
foreach (var page in result.Pages)
{
Console.WriteLine($"Page {page.PageNumber}:");
Console.WriteLine(page.Text);
}Imports IronOcr
Dim ocr As New IronTesseract()
Using input As New OcrInput()
Dim pageIndices As Integer() = {0, 1, 2}
input.LoadImageFrames("scanned-documents.tiff", pageIndices)
' Correct skew and remove noise before reading
input.Deskew()
input.DeNoise()
Dim result As OcrResult = ocr.Read(input)
For Each page In result.Pages
Console.WriteLine($"Page {page.PageNumber}:")
Console.WriteLine(page.Text)
Next
End Using多頁TIFF文件的OCR輸出

Deskew將圖像旋轉以校正平板掃描儀引入的任何傾斜。 DeNoise去除對Tesseract引擎造成困惑的斑點和JPEG影像。這兩個預處理濾鏡共同顯著提高了低質量掃描件的識別準確性。
對於困難的來源材料,提供了額外的OcrInput濾鏡:
input.Sharpen()-- 增強模糊圖像的邊緣對比度input.Binarize()-- 將文件轉為黑白以適用於傳真品質文件input.Scale(200)-- 將小圖像放大以獲得更好的字元分離input.Rotate(90)-- 校正旋轉的文件方向
查看IronOCR圖像濾鏡指南,了解完整的預處理選項列表以及何時應用它們。
您如何配置OCR的語言支持?
預設情況下,IronOCR會讀取英文文字。 若要處理其他語言的文件,請安裝匹配的語言NuGet套件並在Language屬性。
然後配置引擎,對於雙語文件,新增次要語言:
using IronOcr;
using IronOcr.Languages;
var ocr = new IronTesseract();
ocr.Language = OcrLanguage.German;
// For bilingual documents (e.g. Canadian forms, EU directives)
ocr.AddSecondaryLanguage(OcrLanguage.French);
using var input = new OcrInput();
input.LoadImage("german-invoice.png");
OcrResult result = ocr.Read(input);
Console.WriteLine(result.Text);Imports IronOcr
Imports IronOcr.Languages
Dim ocr As New IronTesseract()
ocr.Language = OcrLanguage.German
' For bilingual documents (e.g. Canadian forms, EU directives)
ocr.AddSecondaryLanguage(OcrLanguage.French)
Using input As New OcrInput()
input.LoadImage("german-invoice.png")
Dim result As OcrResult = ocr.Read(input)
Console.WriteLine(result.Text)
End UsingIronOCR支持超過125種語言,每種語言作為單獨的輕量級NuGet套件提供。 這保持了您的生產二進位文件的精簡化--僅包括應用程式實際需要的語言資料。 當您呼叫AddSecondaryLanguage時,引擎在識別過程中混合主語言和輔助語言模型。
您如何處理OCR錯誤並改善識別結果?
生產應用程式需要對OCR管道進行錯誤處理。圖像質量問題、文件遺失或不支持的格式可能會導致例外情況。 將呼叫包裹在try/catch 塊中可提供潔淨的恢復路徑。
using IronOcr;
var ocr = new IronTesseract();
ocr.Language = OcrLanguage.English;
try
{
using var input = new OcrInput();
input.LoadImage("document.png");
input.DeNoise();
input.Deskew();
OcrResult result = ocr.Read(input);
if (result.Text.Length > 0)
{
Console.WriteLine("Recognised text:");
Console.WriteLine(result.Text);
}
else
{
Console.WriteLine("No text was detected in the image.");
}
}
catch (Exception ex)
{
Console.WriteLine($"OCR error: {ex.Message}");
}Imports IronOcr
Dim ocr As New IronTesseract()
ocr.Language = OcrLanguage.English
Try
Using input As New OcrInput()
input.LoadImage("document.png")
input.DeNoise()
input.Deskew()
Dim result As OcrResult = ocr.Read(input)
If result.Text.Length > 0 Then
Console.WriteLine("Recognised text:")
Console.WriteLine(result.Text)
Else
Console.WriteLine("No text was detected in the image.")
End If
End Using
Catch ex As Exception
Console.WriteLine($"OCR error: {ex.Message}")
End Try一些在預期準確性較低時有助於提高準確性的重要設置:
ocr.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.Auto-- 讓Tesseract自動選擇單列、多列和單詞佈局ocr.Configuration.ReadBarCodes = false-- 若您處理的僅是文字文件且希望更快的處理速度,可禁用條形碼檢測ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5-- 確保使用最快的可用引擎
對於欄位出現在可預測位置的結構化表單,請使用基於區域的OCR僅讀取重要區域:
using IronOcr;
using IronSoftware.Drawing;
var ocr = new IronTesseract();
using var input = new OcrInput();
var region = new CropRectangle(x: 50, y: 200, width: 600, height: 100);
input.LoadImage("form.png", region);
OcrResult result = ocr.Read(input);
Console.WriteLine(result.Text);Imports IronOcr
Imports IronSoftware.Drawing
Dim ocr As New IronTesseract()
Using input As New OcrInput()
Dim region As New CropRectangle(x:=50, y:=200, width:=600, height:=100)
input.LoadImage("form.png", region)
Dim result As OcrResult = ocr.Read(input)
Console.WriteLine(result.Text)
End Using限制識別到裁剪矩形可將大型圖像的處理時間減少最多90%。 這一技術特別適合提取發票號碼、表單欄位讀取和身份文件掃描。 更多詳情請參見區域OCR使用指南。
您如何建立可搜尋的PDF文件?
將掃描圖像檔案轉換為可搜尋的PDF文件是最有價值的OCR用例之一。 生成的文件保留了原始視覺外觀,並嵌入了不可見的文字層,PDF查看器、搜索引擎和螢幕閱讀器可以對其進行索引。
using IronOcr;
var ocr = new IronTesseract();
using var input = new OcrInput();
input.Title = "Quarterly Report Q1 2026";
input.LoadImage("page1.png");
input.LoadImage("page2.png");
input.LoadImage("page3.png");
OcrResult result = ocr.Read(input);
result.SaveAsSearchablePdf("searchable-output.pdf");
Console.WriteLine("Searchable PDF created.");
Console.WriteLine($"Pages processed: {result.Pages.Count}");Imports IronOcr
Dim ocr As New IronTesseract()
Using input As New OcrInput()
input.Title = "Quarterly Report Q1 2026"
input.LoadImage("page1.png")
input.LoadImage("page2.png")
input.LoadImage("page3.png")
Dim result As OcrResult = ocr.Read(input)
result.SaveAsSearchablePdf("searchable-output.pdf")
Console.WriteLine("Searchable PDF created.")
Console.WriteLine($"Pages processed: {result.Pages.Count}")
End Using輸出可搜尋PDF文件

SaveAsSearchablePdf寫入一個PDF/A相容文件,其中每個識別的字在原始圖像的準確像素坐標上。 Adobe Acrobat、macOS上的Preview和Foxit Reader都支持在這些文件中全文字搜索,並可在生成後立即使用。
對於基於Web的文件查看器或下游NLP管道,請改用result.SaveAsHocrFile("output.hocr")。 hOCR格式是一個開放的XML標準,將每個單詞的邊界框與文字一起編碼,能夠進行使用者端搜尋時突出顯示和單詞級別的可存取性註釋。
從OcrResult可獲得的其他輸出格式:
result.SaveAsHocrFile("output.hocr")-- 帶有位置資料的hOCR XMLresult.ToXDocument()-- 用於程式處理的LINQ-查詢XDocumentresult.Pages[0].Text-- 適用於流式管線的逐頁純文字
對於已經使用IronPDF的應用程式,您可以將OcrResult直接驅動到PDF生成工作流中,結合OCR提取和PDF編輯於單一.NET過程中。
您如何同時讀取條碼和文字?
IronOCR可以讀取嵌入在列印文字中的條碼和QR碼,而不需要運行單獨的條碼程式庫。 只需一個配置屬性即可啟用此功能:
using IronOcr;
var ocr = new IronTesseract();
ocr.Configuration.ReadBarCodes = true;
using var input = new OcrInput();
input.LoadImage("shipping-label.png");
OcrResult result = ocr.Read(input);
Console.WriteLine("Text:");
Console.WriteLine(result.Text);
Console.WriteLine("Barcodes:");
foreach (var barcode in result.Barcodes)
{
Console.WriteLine($" {barcode.Format}: {barcode.Value}");
}IRON VB CONVERTER ERROR developers@ironsoftware.com支持的條碼格式包括Code 128、Code 39、EAN-13、EAN-8、UPC-A、UPC-E、PDF417、Data Matrix和QR碼。 請參見IronOCR條碼讀取指南以獲取詳細資訊。
此功能在物流、醫療保健和零售應用中特別有用,這些應用中的運單標籤、病人腕帶和產品標籤同時包含可人工閱讀的文字和可機器讀取的條碼。
您如何比較IronOCR與其他.NET OCR選項?
評估.NET OCR程式庫的開發人員通常會考慮IronOCR、Tesseract.NET和雲服務,例如Google Cloud Vision或Azure Computer Vision。 下表總結了主要區別:
| 標準 | IronOCR | Tesseract.NET | Azure Computer Vision |
|---|---|---|---|
| 部署 | 本地或雲端,無需外部調用 | 本地 | 僅雲端,需要網路連接 |
| 安裝 | 單個NuGet套件 | 多個套件+原生二進位文件 | SDK+Azure訂閱 |
| 語言包 | 125+通過NuGet套件提供 | 手動下載tessdata | 由Azure管理 |
| 可搜尋的PDF輸出 | 內建一個方法調用 | 未包含 | 未包含 |
| 圖像預處理 | 12+內建濾鏡 | 需要手動預處理 | 自動(伺服器端) |
| 價格模式 | 一次性永久授權 | 開源(Apache 2.0) | 按次計費 |
Tesseract由Google作為開源項目維護,在內部為IronOCR和Tesseract.NET提供動力。 IronOCR增加了.NET符合習慣的打包、自動模型管理和生產輸出功能(可搜尋的PDF、hOCR輸出),而這些功能是原始Tesseract綁定所缺乏的。 Azure Computer Vision提供了最先進的雲端準確性,但引入了網路延遲和按次成本,不適合高容量或離線工作流。
在資料隱私法規禁止將文件發送至外部服務的情況下——例如醫療記錄、法律文件、財務報表——像IronOCR這樣的本地程式庫是合適的選擇。
您的下一步是什麼?
您現在擁有了向任何.NET 10應用程式新增OCR的基礎:通過NuGet安裝、基本圖像到文字的提取、多頁TIFF處理、語言配置、錯誤處理、基於區域的讀取、條碼檢測和可搜尋的PDF生成。
若要進一步了解,請探索這些IronOCR資源:
- IronOCR文件主頁 -- 完整的API參考和功能指南
- 圖像濾鏡教程 -- 各種預處理濾鏡的詳細指南
- 條碼讀取指南 -- 與文字一起讀取QR碼和線條條碼
- 區域OCR使用指南 -- 基於裁剪的表單和身份證件識別
- 語言參考 -- 支持的125+種語言的完整列表
- API參考 -- 所有類別、方法和屬性
如有關授權問題或需要在生產環境中部署IronOCR,請存取IronOCR授權頁面。 在您的評估期間,免費試用授權可去除輸出水印,而Iron Software的支持團隊在任何層次上都可為技術問題提供幫助。
相關文章


