如何在 C# 中從圖片中擷取文字

C# OCR Image to Text Tutorial: Convert Images to Text Without Tesseract

This article was translated from English: Does it need improvement?
Translated
View the article in English

想在 C# 中將圖片轉換為文字,卻不想費心處理複雜的 Tesseract 設定嗎? 這份詳盡的 IronOCR C# 教學指南將向您展示,如何僅透過幾行程式碼,就在您的 .NET 應用程式中實作強大的光學字元辨識功能。

快速入門:一行程式碼從圖片中擷取文字

此範例展示了 IronOCR 有多麼容易上手——只需一行 C# 程式碼,即可將您的圖片轉為文字。 此範例展示了如何初始化 OCR 引擎,並在無需複雜設定的情況下立即讀取與擷取文字。

  1. using NuGet 套件管理員安裝 https://www.nuget.org/packages/IronOcr

    PM > Install-Package IronOcr
  2. 請複製並執行此程式碼片段。

    string text = new IronTesseract().Read("image.png").Text;
  3. 部署至您的生產環境進行測試

    立即透過免費試用,在您的專案中開始使用 IronOCR

    arrow pointer

如何在 .NET 應用程式中讀取圖片中的文字?

若要在您的 .NET 應用程式中實現 C# OCR 圖像轉文字功能,您需要一個可靠的 OCR 函式庫。 IronOCR 透過 IronOcr.IronTesseract 類別提供一種受管解決方案,能在無需外部依賴項的情況下,同時最大化準確度與速度。

首先,請將 IronOCR 安裝至您的 Visual Studio 專案中。 您可以直接下載 IronOCR DLL,或使用 NuGet 套件管理員

Install-Package IronOcr

為何選擇 IronOCR 作為不使用 Tesseract 的 C# OCR 解決方案?

當您需要在 C# 中將圖像轉換為文字時,IronOCR 相較於傳統的 Tesseract 實作方案,具有顯著優勢:

  • 可在純 .NET 環境中立即運作
  • 無需安裝或設定 Tesseract
  • 支援最新版本引擎:Tesseract 5(Plus Tesseract 4 與 3)
  • 相容於 .NET Framework 4.6.2 以上、.NET Standard 2 以上,以及 .NET Core 2、3、5、6、7、8、9 和 10
  • 相較於原生 Tesseract,能提升準確度與速度
  • 支援 Xamarin、Mono、Azure 及 Docker 部署
  • 透過 NuGet 套件管理複雜的 Tesseract 字典
  • 自動處理 PDF、多幀 TIFF 以及所有主要圖像格式
  • 修正低品質及傾斜的掃描圖像,以獲得最佳效果

如何使用 IronOCR C# 教學指南進行基礎 OCR?

此 Iron Tesseract C# 範例展示了使用 IronOcr 從圖像中讀取文字的最簡單方法。 IronOcr.IronTesseract 類別會擷取文字並將其作為字串傳回。

// Basic C# OCR image to text conversion using IronOCR
// This example shows how to extract text from images without complex setup

using IronOcr;
using System;

try
{
    // Initialize IronTesseract for OCR operations
    var ocrEngine = new IronTesseract();

    // Path to your image file - supports PNG, JPG, TIFF, BMP, and more
    var imagePath = @"img\Screenshot.png";

    // Create input and perform OCR to convert image to text
    using (var input = new OcrInput(imagePath))
    {
        // Read text from image and get results
        OcrResult result = ocrEngine.Read(input);

        // Display extracted text
        Console.WriteLine(result.Text);
    }
}
catch (OcrException ex)
{
    // Handle OCR-specific errors
    Console.WriteLine($"OCR Error: {ex.Message}");
}
catch (Exception ex)
{
    // Handle general errors
    Console.WriteLine($"Error: {ex.Message}");
}
// Basic C# OCR image to text conversion using IronOCR
// This example shows how to extract text from images without complex setup

using IronOcr;
using System;

try
{
    // Initialize IronTesseract for OCR operations
    var ocrEngine = new IronTesseract();

    // Path to your image file - supports PNG, JPG, TIFF, BMP, and more
    var imagePath = @"img\Screenshot.png";

    // Create input and perform OCR to convert image to text
    using (var input = new OcrInput(imagePath))
    {
        // Read text from image and get results
        OcrResult result = ocrEngine.Read(input);

        // Display extracted text
        Console.WriteLine(result.Text);
    }
}
catch (OcrException ex)
{
    // Handle OCR-specific errors
    Console.WriteLine($"OCR Error: {ex.Message}");
}
catch (Exception ex)
{
    // Handle general errors
    Console.WriteLine($"Error: {ex.Message}");
}
' Basic C# OCR image to text conversion using IronOCR
' This example shows how to extract text from images without complex setup

Imports IronOcr
Imports System

Try
	' Initialize IronTesseract for OCR operations
	Dim ocrEngine = New IronTesseract()

	' Path to your image file - supports PNG, JPG, TIFF, BMP, and more
	Dim imagePath = "img\Screenshot.png"

	' Create input and perform OCR to convert image to text
	Using input = New OcrInput(imagePath)
		' Read text from image and get results
		Dim result As OcrResult = ocrEngine.Read(input)

		' Display extracted text
		Console.WriteLine(result.Text)
	End Using
Catch ex As OcrException
	' Handle OCR-specific errors
	Console.WriteLine($"OCR Error: {ex.Message}")
Catch ex As Exception
	' Handle general errors
	Console.WriteLine($"Error: {ex.Message}")
End Try
$vbLabelText   $csharpLabel

此程式碼在清晰圖像上可達到 100% 的準確度,能精確提取圖像中顯示的文字:

IronOCR Simple Example

In this simple example we test the accuracy of our C# OCR library to read text from a PNG Image. This is a very basic test, but things will get more complicated as the tutorial continues.

The quick brown fox jumps over the lazy dog

IronTesseract 類別會在內部處理複雜的 OCR 操作。 它能自動掃描對齊、優化解析度,並透過 IronOCR 運用人工智慧從圖像中讀取文字,準確度媲美人類。

儘管幕後進行著複雜的處理流程——包括影像分析、引擎優化及智慧型文字辨識——OCR 處理過程仍能與人類閱讀速度同步,同時維持極高的準確度。

IronOCR 簡單範例:展示 C# OCR 圖像轉文字轉換,準確度達 100% 展示 IronOCR 能夠以完美準確度從 PNG 圖片中擷取文字的螢幕截圖

如何在不配置 Tesseract 的情況下實作進階 C# OCR?

若在 C# 中將圖片轉換為文字時,生產環境應用程式需要最佳效能,請同時使用 OcrInputIronTesseract 類別。 此方法可對 OCR 流程進行精細控制。

OcrInput 類別功能

  • 支援多種圖像格式:JPEG、TIFF、GIF、BMP、PNG
  • 匯入完整的 PDF 檔案或特定頁面
  • 自動增強對比度、解析度與影像品質
  • 修正旋轉、掃描雜訊、傾斜及負片影像

IronTesseract 類別功能

  • 支援 127 種以上預先封裝的語言
  • 內建 Tesseract 5、4 及 3 引擎
  • 文件類型說明(螢幕截圖、程式碼片段或完整文件)
  • 整合BarCode讀取功能
  • 多種輸出格式:可搜尋的 PDF、HOCR HTML、DOM 物件及字串

如何開始使用 OcrInputIronTesseract

以下是針對此 IronOCR C# 教學指南的建議設定,適用於大多數文件類型:

using IronOcr;

// Initialize IronTesseract for advanced OCR operations
IronTesseract ocr = new IronTesseract();

// Create input container for processing multiple images
using (OcrInput input = new OcrInput())
{
    // Process specific pages from multi-page TIFF files
    int[] pageIndices = new int[] { 1, 2 };

    // Load TIFF frames - perfect for scanned documents
    input.LoadImageFrames(@"img\Potter.tiff", pageIndices);

    // Execute OCR to read text from image using IronOCR
    OcrResult result = ocr.Read(input);

    // Output the extracted text
    Console.WriteLine(result.Text);
}
using IronOcr;

// Initialize IronTesseract for advanced OCR operations
IronTesseract ocr = new IronTesseract();

// Create input container for processing multiple images
using (OcrInput input = new OcrInput())
{
    // Process specific pages from multi-page TIFF files
    int[] pageIndices = new int[] { 1, 2 };

    // Load TIFF frames - perfect for scanned documents
    input.LoadImageFrames(@"img\Potter.tiff", pageIndices);

    // Execute OCR to read text from image using IronOCR
    OcrResult result = ocr.Read(input);

    // Output the extracted text
    Console.WriteLine(result.Text);
}
Imports IronOcr

' Initialize IronTesseract for advanced OCR operations
Private ocr As New IronTesseract()

' Create input container for processing multiple images
Using input As New OcrInput()
	' Process specific pages from multi-page TIFF files
	Dim pageIndices() As Integer = { 1, 2 }

	' Load TIFF frames - perfect for scanned documents
	input.LoadImageFrames("img\Potter.tiff", pageIndices)

	' Execute OCR to read text from image using IronOCR
	Dim result As OcrResult = ocr.Read(input)

	' Output the extracted text
	Console.WriteLine(result.Text)
End Using
$vbLabelText   $csharpLabel

此設定在中等品質的掃描文件上,始終能達到近乎完美的準確度。 LoadImageFrames 方法能高效處理多頁文件,使其成為批次處理情境的理想選擇。


多頁 TIFF 文件,顯示可供 C# OCR 處理的《哈利波特》文本

展示 IronOCR 多頁文字擷取功能的 TIFF 範例文件

IronOCR 能夠從 TIFF 等掃描文件中的圖像和 BarCode 讀取文字,這充分展現了它如何簡化複雜的 OCR 任務。 此函式庫在處理實際文件方面表現出色,能無縫處理多頁 TIFF 檔案並進行 PDF 文字擷取

IronOCR 如何處理低品質的掃描檔?


這張帶有數位雜訊的低品質掃描圖,展示了 IronOCR 的影像增強能力

IronOCR 可透過影像濾鏡精確處理此類低解析度且帶有雜訊的文件

在處理含有變形與數位雜訊的不完美掃描檔時,IronOCR 的表現優於其他 C# OCR 程式庫。 本翻譯專為實際應用情境設計,而非針對完美無瑕的測試圖像。

// Advanced Iron Tesseract C# example for low-quality images
using IronOcr;
using System;

var ocr = new IronTesseract();

try
{
    using (var input = new OcrInput())
    {
        // Load specific pages from poor-quality TIFF
        var pageIndices = new int[] { 0, 1 };
        input.LoadImageFrames(@"img\Potter.LowQuality.tiff", pageIndices);

        // Apply deskew filter to correct rotation and perspective
        input.Deskew(); // Critical for improving accuracy on skewed scans

        // Perform OCR with enhanced preprocessing
        OcrResult result = ocr.Read(input);

        // Display results
        Console.WriteLine("Recognized Text:");
        Console.WriteLine(result.Text);
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Error during OCR: {ex.Message}");
}
// Advanced Iron Tesseract C# example for low-quality images
using IronOcr;
using System;

var ocr = new IronTesseract();

try
{
    using (var input = new OcrInput())
    {
        // Load specific pages from poor-quality TIFF
        var pageIndices = new int[] { 0, 1 };
        input.LoadImageFrames(@"img\Potter.LowQuality.tiff", pageIndices);

        // Apply deskew filter to correct rotation and perspective
        input.Deskew(); // Critical for improving accuracy on skewed scans

        // Perform OCR with enhanced preprocessing
        OcrResult result = ocr.Read(input);

        // Display results
        Console.WriteLine("Recognized Text:");
        Console.WriteLine(result.Text);
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Error during OCR: {ex.Message}");
}
' Advanced Iron Tesseract C# example for low-quality images
Imports IronOcr
Imports System

Private ocr = New IronTesseract()

Try
	Using input = New OcrInput()
		' Load specific pages from poor-quality TIFF
		Dim pageIndices = New Integer() { 0, 1 }
		input.LoadImageFrames("img\Potter.LowQuality.tiff", pageIndices)

		' Apply deskew filter to correct rotation and perspective
		input.Deskew() ' Critical for improving accuracy on skewed scans

		' Perform OCR with enhanced preprocessing
		Dim result As OcrResult = ocr.Read(input)

		' Display results
		Console.WriteLine("Recognized Text:")
		Console.WriteLine(result.Text)
	End Using
Catch ex As Exception
	Console.WriteLine($"Error during OCR: {ex.Message}")
End Try
$vbLabelText   $csharpLabel

using Input.Deskew() 後,低品質掃描文件的準確度提升至 99.8%,幾乎可媲美高品質掃描結果。 這正說明了為何 IronOCR 是 C# OCR 的首選方案,且無需面對 Tesseract 的複雜問題。

圖片濾鏡可能會稍微增加處理時間,但能顯著縮短整體 OCR 所需時間。 如何取得適當的平衡,取決於您的文件品質。

在大多數情況下,Input.Deskew()Input.DeNoise() 能有效提升 OCR 效能。 進一步了解影像預處理技術

如何優化 OCR 的效能與速度?

在 C# 中將圖像轉換為文字時,影響 OCR 速度的最重要因素是輸入品質。 較高的 DPI(約 200 dpi)搭配最低的雜訊,可產生最快且最精確的結果。

雖然 IronOCR 在修正品質不佳的文件方面表現出色,但這項功能會增加額外的處理時間。

請選擇壓縮失真最少的圖像格式。 由於數位雜訊較低,TIFF 和 PNG 通常比 JPEG 能產生更快的處理結果。

哪些影像濾鏡能提升 OCR 速度?

以下篩選器可顯著提升您的 C# OCR 圖像轉文字工作流程的效能:

  • OcrInput.Rotate(double degrees)將圖片順時針旋轉(負值表示逆時針旋轉)
  • OcrInput.Binarize()轉換為黑白,以提升低對比度情境下的效能
  • OcrInput.ToGrayScale()轉換為灰階以提升潛在執行速度
  • OcrInput.Co/ntrast()自動調整對比度以提升準確性
  • OcrInput.DeNoise()在預期出現雜訊時移除數位偽影
  • OcrInput.Invert()將文字顏色反轉為黑底白字
  • OcrInput.Dilate()擴展文字邊界
  • OcrInput.Erode(): 縮減文字邊界
  • OcrInput.Deskew()修正對齊問題——對於排版歪斜的文件至關重要
  • OcrInput.DeepCleanBackgroundNoise()強力雜訊消除
  • OcrInput.EnhanceResolution改善低解析度影像的畫質
  • OcrInput.DetectPageOrientation():偵測並修正頁面旋轉。 傳入 OrientationDetectionMode 參數以控制精準度與速度的權衡:DetailedExtremeDetailed(新增於 v2025.8.6)

Scale()EnhanceResolution() 因 v2025.12.3 版本中的已知問題,無法與 SaveAsSearchablePdf() 相容。所有其他篩選器在可搜尋 PDF/A 輸出時皆能正常運作。

如何設定 IronOCR 以達到最高速度?

請使用以下設定來優化處理高品質掃描檔的速度:

using IronOcr;

// Configure for speed - ideal for clean documents
IronTesseract ocr = new IronTesseract();

// Exclude problematic characters to speed up recognition
ocr.Co/nfiguration.BlackListCharacters = "~`$#^*_{[]}|\\";

// Use automatic page segmentation
ocr.Co/nfiguration.PageSegmentationMode = TesseractPageSegmentationMode.Auto;

// Select fast English language pack
ocr.Language = OcrLanguage.EnglishFast;

using (OcrInput input = new OcrInput())
{
    // Load specific pages from document
    int[] pageIndices = new int[] { 1, 2 };
    input.LoadImageFrames(@"img\Potter.tiff", pageIndices);

    // Read with optimized settings
    OcrResult result = ocr.Read(input);
    Console.WriteLine(result.Text);
}
using IronOcr;

// Configure for speed - ideal for clean documents
IronTesseract ocr = new IronTesseract();

// Exclude problematic characters to speed up recognition
ocr.Co/nfiguration.BlackListCharacters = "~`$#^*_{[]}|\\";

// Use automatic page segmentation
ocr.Co/nfiguration.PageSegmentationMode = TesseractPageSegmentationMode.Auto;

// Select fast English language pack
ocr.Language = OcrLanguage.EnglishFast;

using (OcrInput input = new OcrInput())
{
    // Load specific pages from document
    int[] pageIndices = new int[] { 1, 2 };
    input.LoadImageFrames(@"img\Potter.tiff", pageIndices);

    // Read with optimized settings
    OcrResult result = ocr.Read(input);
    Console.WriteLine(result.Text);
}
Imports IronOcr

' Configure for speed - ideal for clean documents
Dim ocr As New IronTesseract()

' Exclude problematic characters to speed up recognition
ocr.Configuration.BlackListCharacters = "~`$#^*_{[]}|\"

' Use automatic page segmentation
ocr.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.Auto

' Select fast English language pack
ocr.Language = OcrLanguage.EnglishFast

Using input As New OcrInput()
    ' Load specific pages from document
    Dim pageIndices As Integer() = {1, 2}
    input.LoadImageFrames("img\Potter.tiff", pageIndices)

    ' Read with optimized settings
    Dim result As OcrResult = ocr.Read(input)
    Console.WriteLine(result.Text)
End Using
$vbLabelText   $csharpLabel

此最佳化設定在維持 99.8% 準確度的同時,相較於預設設定,處理速度提升了 35%

如何使用 C# OCR 讀取圖片的特定區域?

下方的 Iron Tesseract C# 範例展示了如何使用 System.Drawing.Rectangle 針對特定地區進行設定。 此技術對於處理文字出現在可預測位置的標準化表單而言,極具價值。

IronOCR 能否處理裁切區域以加快處理速度?

透過使用像素座標,您可以將 OCR 限制在特定區域,大幅提升速度並防止不必要的文字被擷取:

using IronOcr;
using IronSoftware.Drawing;

// Initialize OCR engine for targeted region processing
var ocr = new IronTesseract();

using (var input = new OcrInput())
{
    // Define exact region for OCR - coordinates in pixels
    var contentArea = new System.Drawing.Rectangle(
        x: 215, 
        y: 1250, 
        width: 1335, 
        height: 280
    );

    // Load image with specific area - perfect for forms and invoices
    input.LoadImage("img/ComSci.png", contentArea);

    // Process only the defined region
    OcrResult result = ocr.Read(input);
    Console.WriteLine(result.Text);
}
using IronOcr;
using IronSoftware.Drawing;

// Initialize OCR engine for targeted region processing
var ocr = new IronTesseract();

using (var input = new OcrInput())
{
    // Define exact region for OCR - coordinates in pixels
    var contentArea = new System.Drawing.Rectangle(
        x: 215, 
        y: 1250, 
        width: 1335, 
        height: 280
    );

    // Load image with specific area - perfect for forms and invoices
    input.LoadImage("img/ComSci.png", contentArea);

    // Process only the defined region
    OcrResult result = ocr.Read(input);
    Console.WriteLine(result.Text);
}
Imports IronOcr
Imports IronSoftware.Drawing

' Initialize OCR engine for targeted region processing
Dim ocr As New IronTesseract()

Using input As New OcrInput()
    ' Define exact region for OCR - coordinates in pixels
    Dim contentArea As New System.Drawing.Rectangle(215, 1250, 1335, 280)

    ' Load image with specific area - perfect for forms and invoices
    input.LoadImage("img/ComSci.png", contentArea)

    ' Process only the defined region
    Dim result As OcrResult = ocr.Read(input)
    Console.WriteLine(result.Text)
End Using
$vbLabelText   $csharpLabel

這種針對性的方法在僅提取相關文字的同時,提供了 41% 的速度提升。 此工具特別適用於結構化文件,例如發票、支票及表單。 相同的裁切技術可與 PDF OCR 操作無縫整合。

展示 C# 語言中目標 OCR 區域擷取的電腦科學文件 展示 IronOCR 矩形選取功能進行精確區域文字擷取的範例文件

IronOCR 支援多少種語言?

IronOCR 透過便捷的語言套件提供 127 種國際語言。 您可從我們的網站或透過 NuGet 套件管理員下載這些 DLL 檔案。

請透過 NuGet 介面安裝語言套件(搜尋"IronOcr.Languages"),或瀏覽完整的語言套件清單

支援的語言包括阿拉伯語、中文(簡體/繁體)、日語、韓語、印地語、俄語、德語、法語、西班牙語,以及 115 種以上的其他語言,每種語言均經過優化以確保精準的文字辨識。

如何在多種語言中實作 OCR?

此 IronOCR C# 教學範例展示了阿拉伯文的文字辨識:

Install-Package IronOcr.Languages.Arabic
IronOCR 正在處理阿拉伯文,展示其多語言 OCR 支援功能

IronOCR 可從 GIF 圖像中精準擷取阿拉伯文

// Install-Package IronOcr.Languages.Arabic
using IronOcr;

// Configure for Arabic language OCR
var ocr = new IronTesseract();
ocr.Language = OcrLanguage.Arabic;

using (var input = new OcrInput())
{
    // Load Arabic text image
    input.LoadImage("img/arabic.gif");

    // IronOCR handles low-quality Arabic text that standard Tesseract cannot
    var result = ocr.Read(input);

    // Save to file (console may not display Arabic correctly)
    result.SaveAsTextFile("arabic.txt");
}
// Install-Package IronOcr.Languages.Arabic
using IronOcr;

// Configure for Arabic language OCR
var ocr = new IronTesseract();
ocr.Language = OcrLanguage.Arabic;

using (var input = new OcrInput())
{
    // Load Arabic text image
    input.LoadImage("img/arabic.gif");

    // IronOCR handles low-quality Arabic text that standard Tesseract cannot
    var result = ocr.Read(input);

    // Save to file (console may not display Arabic correctly)
    result.SaveAsTextFile("arabic.txt");
}
Imports IronOcr

' Configure for Arabic language OCR
Dim ocr As New IronTesseract()
ocr.Language = OcrLanguage.Arabic

Using input As New OcrInput()
    ' Load Arabic text image
    input.LoadImage("img/arabic.gif")

    ' IronOCR handles low-quality Arabic text that standard Tesseract cannot
    Dim result = ocr.Read(input)

    ' Save to file (console may not display Arabic correctly)
    result.SaveAsTextFile("arabic.txt")
End Using
$vbLabelText   $csharpLabel

IronOCR 能否處理多語言文件?

當文件包含多種語言時,請設定 IronOCR 以支援多語言功能:

Install-Package IronOcr.Languages.ChineseSimplified
// Multi-language OCR configuration
using IronOcr;

var ocr = new IronTesseract();

// Set primary language
ocr.Language = OcrLanguage.ChineseSimplified;

// Add secondary languages as needed
ocr.AddSecondaryLanguage(OcrLanguage.English);

// Custom .traineddata files can be added for specialized recognition
// ocr.AddSecondaryLanguage("path/to/custom.traineddata");

using (var input = new OcrInput())
{
    // Process multi-language document
    input.LoadImage("img/MultiLanguage.jpeg");

    var result = ocr.Read(input);
    result.SaveAsTextFile("MultiLanguage.txt");
}
// Multi-language OCR configuration
using IronOcr;

var ocr = new IronTesseract();

// Set primary language
ocr.Language = OcrLanguage.ChineseSimplified;

// Add secondary languages as needed
ocr.AddSecondaryLanguage(OcrLanguage.English);

// Custom .traineddata files can be added for specialized recognition
// ocr.AddSecondaryLanguage("path/to/custom.traineddata");

using (var input = new OcrInput())
{
    // Process multi-language document
    input.LoadImage("img/MultiLanguage.jpeg");

    var result = ocr.Read(input);
    result.SaveAsTextFile("MultiLanguage.txt");
}
Imports IronOcr

' Multi-language OCR configuration
Dim ocr As New IronTesseract()

' Set primary language
ocr.Language = OcrLanguage.ChineseSimplified

' Add secondary languages as needed
ocr.AddSecondaryLanguage(OcrLanguage.English)

' Custom .traineddata files can be added for specialized recognition
' ocr.AddSecondaryLanguage("path/to/custom.traineddata")

Using input As New OcrInput()
    ' Process multi-language document
    input.LoadImage("img/MultiLanguage.jpeg")

    Dim result = ocr.Read(input)
    result.SaveAsTextFile("MultiLanguage.txt")
End Using
$vbLabelText   $csharpLabel

如何使用 C# OCR 處理多頁文件?

IronOCR 可將多頁文件或圖片無縫整合為單一 OcrResult。 此功能可實現強大的功能,例如建立可搜尋的 PDF 檔案,以及從整組文件中擷取文字。

在單一 OCR 操作中混合搭配各種來源——圖片、TIFF 幀和 PDF 頁面:

// Multi-source document processing
using IronOcr;

IronTesseract ocr = new IronTesseract();

using (OcrInput input = new OcrInput())
{
    // Add various image formats
    input.LoadImage("image1.jpeg");
    input.LoadImage("image2.png");

    // Process specific frames from multi-frame images
    int[] frameNumbers = { 1, 2 };
    input.LoadImageFrames("image3.gif", frameNumbers);

    // Process all sources together
    OcrResult result = ocr.Read(input);

    // Verify page count
    Console.WriteLine($"{result.Pages.Co/unt} Pages processed.");
}
// Multi-source document processing
using IronOcr;

IronTesseract ocr = new IronTesseract();

using (OcrInput input = new OcrInput())
{
    // Add various image formats
    input.LoadImage("image1.jpeg");
    input.LoadImage("image2.png");

    // Process specific frames from multi-frame images
    int[] frameNumbers = { 1, 2 };
    input.LoadImageFrames("image3.gif", frameNumbers);

    // Process all sources together
    OcrResult result = ocr.Read(input);

    // Verify page count
    Console.WriteLine($"{result.Pages.Co/unt} Pages processed.");
}
Imports IronOcr

Dim ocr As New IronTesseract()

Using input As New OcrInput()
    ' Add various image formats
    input.LoadImage("image1.jpeg")
    input.LoadImage("image2.png")

    ' Process specific frames from multi-frame images
    Dim frameNumbers As Integer() = {1, 2}
    input.LoadImageFrames("image3.gif", frameNumbers)

    ' Process all sources together
    Dim result As OcrResult = ocr.Read(input)

    ' Verify page count
    Console.WriteLine($"{result.Pages.Count} Pages processed.")
End Using
$vbLabelText   $csharpLabel

高效處理 TIFF 檔案的所有頁面:

using IronOcr;

IronTesseract ocr = new IronTesseract();

using (OcrInput input = new OcrInput())
{
    // Define pages to process (0-based indexing)
    int[] pageIndices = new int[] { 0, 1 };

    // Load specific TIFF frames
    input.LoadImageFrames("MultiFrame.Tiff", pageIndices);

    // Extract text from all frames
    OcrResult result = ocr.Read(input);

    Console.WriteLine(result.Text);
    Console.WriteLine($"{result.Pages.Co/unt} Pages processed");
}
using IronOcr;

IronTesseract ocr = new IronTesseract();

using (OcrInput input = new OcrInput())
{
    // Define pages to process (0-based indexing)
    int[] pageIndices = new int[] { 0, 1 };

    // Load specific TIFF frames
    input.LoadImageFrames("MultiFrame.Tiff", pageIndices);

    // Extract text from all frames
    OcrResult result = ocr.Read(input);

    Console.WriteLine(result.Text);
    Console.WriteLine($"{result.Pages.Co/unt} Pages processed");
}
Imports IronOcr

Dim ocr As New IronTesseract()

Using input As New OcrInput()
    ' Define pages to process (0-based indexing)
    Dim pageIndices As Integer() = {0, 1}

    ' Load specific TIFF frames
    input.LoadImageFrames("MultiFrame.Tiff", pageIndices)

    ' Extract text from all frames
    Dim result As OcrResult = ocr.Read(input)

    Console.WriteLine(result.Text)
    Console.WriteLine($"{result.Pages.Count} Pages processed")
End Using
$vbLabelText   $csharpLabel

將 TIFF 或 PDF 檔案轉換為可搜尋格式:

using System;
using IronOcr;

IronTesseract ocr = new IronTesseract();

using (OcrInput input = new OcrInput())
{
    // Set document metadata
    input.Title = "Quarterly Report";

    // Combine multiple sources
    input.LoadImage("image1.jpeg");
    input.LoadImage("image2.png");

    // Add specific frames from animated images
    int[] gifFrames = new int[] { 1, 2 };
    input.LoadImageFrames("image3.gif", gifFrames);

    // Create searchable PDF
    OcrResult result = ocr.Read(input);

    // Pass true to apply any active OcrInput filters to the searchable PDF output (added v2025.5.11)
    result.SaveAsSearchablePdf("searchable.pdf", true);
}
using System;
using IronOcr;

IronTesseract ocr = new IronTesseract();

using (OcrInput input = new OcrInput())
{
    // Set document metadata
    input.Title = "Quarterly Report";

    // Combine multiple sources
    input.LoadImage("image1.jpeg");
    input.LoadImage("image2.png");

    // Add specific frames from animated images
    int[] gifFrames = new int[] { 1, 2 };
    input.LoadImageFrames("image3.gif", gifFrames);

    // Create searchable PDF
    OcrResult result = ocr.Read(input);

    // Pass true to apply any active OcrInput filters to the searchable PDF output (added v2025.5.11)
    result.SaveAsSearchablePdf("searchable.pdf", true);
}
Imports System
Imports IronOcr

Dim ocr As New IronTesseract()

Using input As New OcrInput()
    ' Set document metadata
    input.Title = "Quarterly Report"

    ' Combine multiple sources
    input.LoadImage("image1.jpeg")
    input.LoadImage("image2.png")

    ' Add specific frames from animated images
    Dim gifFrames As Integer() = {1, 2}
    input.LoadImageFrames("image3.gif", gifFrames)

    ' Create searchable PDF
    Dim result As OcrResult = ocr.Read(input)

    ' Pass true to apply any active OcrInput filters to the searchable PDF output (added v2025.5.11)
    result.SaveAsSearchablePdf("searchable.pdf", True)
End Using
$vbLabelText   $csharpLabel

將現有 PDF 檔案轉換為可搜尋版本:

using IronOcr;

var ocr = new IronTesseract();

using (var input = new OcrInput())
{
    // Set PDF metadata
    input.Title = "Annual Report 2024";

    // Process existing PDF
    input.LoadPdf("example.pdf", "password");

    // Generate searchable version
    var result = ocr.Read(input);
    result.SaveAsSearchablePdf("searchable.pdf");
}
using IronOcr;

var ocr = new IronTesseract();

using (var input = new OcrInput())
{
    // Set PDF metadata
    input.Title = "Annual Report 2024";

    // Process existing PDF
    input.LoadPdf("example.pdf", "password");

    // Generate searchable version
    var result = ocr.Read(input);
    result.SaveAsSearchablePdf("searchable.pdf");
}
Imports IronOcr

Private ocr = New IronTesseract()

Using input = New OcrInput()
	' Set PDF metadata
	input.Title = "Annual Report 2024"

	' Process existing PDF
	input.LoadPdf("example.pdf", "password")

	' Generate searchable version
	Dim result = ocr.Read(input)
	result.SaveAsSearchablePdf("searchable.pdf")
End Using
$vbLabelText   $csharpLabel

將相同技巧應用於 TIFF 轉換:

using IronOcr;

var ocr = new IronTesseract();

using (var input = new OcrInput())
{
    // Configure document properties
    input.Title = "Scanned Archive Document";

    // Select pages to process
    var pageIndices = new int[] { 1, 2 };
    input.LoadImageFrames("example.tiff", pageIndices);

    // Create searchable PDF from TIFF
    OcrResult result = ocr.Read(input);
    result.SaveAsSearchablePdf("searchable.pdf");
}
using IronOcr;

var ocr = new IronTesseract();

using (var input = new OcrInput())
{
    // Configure document properties
    input.Title = "Scanned Archive Document";

    // Select pages to process
    var pageIndices = new int[] { 1, 2 };
    input.LoadImageFrames("example.tiff", pageIndices);

    // Create searchable PDF from TIFF
    OcrResult result = ocr.Read(input);
    result.SaveAsSearchablePdf("searchable.pdf");
}
Imports IronOcr

Private ocr = New IronTesseract()

Using input = New OcrInput()
	' Configure document properties
	input.Title = "Scanned Archive Document"

	' Select pages to process
	Dim pageIndices = New Integer() { 1, 2 }
	input.LoadImageFrames("example.tiff", pageIndices)

	' Create searchable PDF from TIFF
	Dim result As OcrResult = ocr.Read(input)
	result.SaveAsSearchablePdf("searchable.pdf")
End Using
$vbLabelText   $csharpLabel

如何將 OCR 結果匯出為 HOCR HTML?

IronOCR 支援 HOCR HTML 匯出功能,可將結構化 PDF 轉換為 HTMLTIFF 轉換為 HTML,同時保留版面配置資訊:

using IronOcr;

var ocr = new IronTesseract();

using (var input = new OcrInput())
{
    // Set HTML title
    input.Title = "Document Archive";

    // Process multiple document types
    input.LoadImage("image2.jpeg");
    input.LoadPdf("example.pdf", "password");

    // Add TIFF pages
    var pageIndices = new int[] { 1, 2 };
    input.LoadImageFrames("example.tiff", pageIndices);

    // Export as HOCR with position data
    OcrResult result = ocr.Read(input);
    result.SaveAsHocrFile("hocr.html");
}
using IronOcr;

var ocr = new IronTesseract();

using (var input = new OcrInput())
{
    // Set HTML title
    input.Title = "Document Archive";

    // Process multiple document types
    input.LoadImage("image2.jpeg");
    input.LoadPdf("example.pdf", "password");

    // Add TIFF pages
    var pageIndices = new int[] { 1, 2 };
    input.LoadImageFrames("example.tiff", pageIndices);

    // Export as HOCR with position data
    OcrResult result = ocr.Read(input);
    result.SaveAsHocrFile("hocr.html");
}
Imports IronOcr

Dim ocr As New IronTesseract()

Using input As New OcrInput()
    ' Set HTML title
    input.Title = "Document Archive"

    ' Process multiple document types
    input.LoadImage("image2.jpeg")
    input.LoadPdf("example.pdf", "password")

    ' Add TIFF pages
    Dim pageIndices As Integer() = {1, 2}
    input.LoadImageFrames("example.tiff", pageIndices)

    ' Export as HOCR with position data
    Dim result As OcrResult = ocr.Read(input)
    result.SaveAsHocrFile("hocr.html")
End Using
$vbLabelText   $csharpLabel

IronOCR 能否同時讀取 BarCode 與文字?

IronOCR 獨特地將文字辨識與 BARCODE 讀取功能結合,無需額外使用其他程式庫:

// Enable combined text and barcode recognition
using IronOcr;

var ocr = new IronTesseract();

// Enable barcode detection
ocr.Co/nfiguration.ReadBarCodes = true;

using (var input = new OcrInput())
{
    // Load image containing both text and barcodes
    input.LoadImage("img/Barcode.png");

    // Process both text and barcodes
    var result = ocr.Read(input);

    // Extract barcode data
    foreach (var barcode in result.Barcodes)
    {
        Console.WriteLine($"Barcode Value: {barcode.Value}");
        Console.WriteLine($"Type: {barcode.Type}, Location: {barcode.Location}");
    }
}
// Enable combined text and barcode recognition
using IronOcr;

var ocr = new IronTesseract();

// Enable barcode detection
ocr.Co/nfiguration.ReadBarCodes = true;

using (var input = new OcrInput())
{
    // Load image containing both text and barcodes
    input.LoadImage("img/Barcode.png");

    // Process both text and barcodes
    var result = ocr.Read(input);

    // Extract barcode data
    foreach (var barcode in result.Barcodes)
    {
        Console.WriteLine($"Barcode Value: {barcode.Value}");
        Console.WriteLine($"Type: {barcode.Type}, Location: {barcode.Location}");
    }
}
Imports IronOcr

Dim ocr As New IronTesseract()

' Enable barcode detection
ocr.Configuration.ReadBarCodes = True

Using input As New OcrInput()
    ' Load image containing both text and barcodes
    input.LoadImage("img/Barcode.png")

    ' Process both text and barcodes
    Dim result = ocr.Read(input)

    ' Extract barcode data
    For Each barcode In result.Barcodes
        Console.WriteLine($"Barcode Value: {barcode.Value}")
        Console.WriteLine($"Type: {barcode.Type}, Location: {barcode.Location}")
    Next
End Using
$vbLabelText   $csharpLabel

如何存取詳細的 OCR 結果與元資料?

IronOCR 的結果物件提供全面性的資料,讓進階開發人員能運用於複雜的應用程式中。

每個 OcrResult 包含分層集合:頁面、段落、行、WORD及字元。 所有元素均包含詳細的元資料,例如位置、字型資訊及信心分數。

個別元素(段落、文字、BARCODE)可匯出為圖片或位圖以供後續處理:

using System;
using IronOcr;
using IronSoftware.Drawing;

// Configure with barcode support
IronTesseract ocr = new IronTesseract
{
    Configuration = { ReadBarCodes = true }
};

using OcrInput input = new OcrInput();

// Process multi-page document
int[] pageIndices = { 1, 2 };
input.LoadImageFrames(@"img\Potter.tiff", pageIndices);

OcrResult result = ocr.Read(input);

// Navigate the complete results hierarchy
foreach (var page in result.Pages)
{
    // Page-level data
    int pageNumber = page.PageNumber;
    string pageText = page.Text;
    int pageWordCount = page.WordCount;

    // Extract page elements
    OcrResult.Barcode[] barcodes = page.Barcodes;
    AnyBitmap pageImage = page.ToBitmap();
    double pageWidth = page.Width;
    double pageHeight = page.Height;

    foreach (var paragraph in page.Paragraphs)
    {
        // Paragraph properties
        int paragraphNumber = paragraph.ParagraphNumber;
        string paragraphText = paragraph.Text;
        double paragraphConfidence = paragraph.Co/nfidence;
        var textDirection = paragraph.TextDirection;

        foreach (var line in paragraph.Lines)
        {
            // Line details including baseline information
            string lineText = line.Text;
            double lineConfidence = line.Co/nfidence;
            double baselineAngle = line.BaselineAngle;
            double baselineOffset = line.BaselineOffset;

            foreach (var word in line.Words)
            {
                // Word-level data
                string wordText = word.Text;
                double wordConfidence = word.Co/nfidence;

                // Font information (when available)
                if (word.Font != null)
                {
                    string fontName = word.Font.FontName;
                    double fontSize = word.Font.FontSize;
                    bool isBold = word.Font.IsBold;
                    bool isItalic = word.Font.IsItalic;
                }

                foreach (var character in word.Characters)
                {
                    // Character-level analysis
                    string charText = character.Text;
                    double charConfidence = character.Co/nfidence;

                    // Alternative character choices for spell-checking
                    OcrResult.Choice[] alternatives = character.Choices;
                }
            }
        }
    }
}
using System;
using IronOcr;
using IronSoftware.Drawing;

// Configure with barcode support
IronTesseract ocr = new IronTesseract
{
    Configuration = { ReadBarCodes = true }
};

using OcrInput input = new OcrInput();

// Process multi-page document
int[] pageIndices = { 1, 2 };
input.LoadImageFrames(@"img\Potter.tiff", pageIndices);

OcrResult result = ocr.Read(input);

// Navigate the complete results hierarchy
foreach (var page in result.Pages)
{
    // Page-level data
    int pageNumber = page.PageNumber;
    string pageText = page.Text;
    int pageWordCount = page.WordCount;

    // Extract page elements
    OcrResult.Barcode[] barcodes = page.Barcodes;
    AnyBitmap pageImage = page.ToBitmap();
    double pageWidth = page.Width;
    double pageHeight = page.Height;

    foreach (var paragraph in page.Paragraphs)
    {
        // Paragraph properties
        int paragraphNumber = paragraph.ParagraphNumber;
        string paragraphText = paragraph.Text;
        double paragraphConfidence = paragraph.Co/nfidence;
        var textDirection = paragraph.TextDirection;

        foreach (var line in paragraph.Lines)
        {
            // Line details including baseline information
            string lineText = line.Text;
            double lineConfidence = line.Co/nfidence;
            double baselineAngle = line.BaselineAngle;
            double baselineOffset = line.BaselineOffset;

            foreach (var word in line.Words)
            {
                // Word-level data
                string wordText = word.Text;
                double wordConfidence = word.Co/nfidence;

                // Font information (when available)
                if (word.Font != null)
                {
                    string fontName = word.Font.FontName;
                    double fontSize = word.Font.FontSize;
                    bool isBold = word.Font.IsBold;
                    bool isItalic = word.Font.IsItalic;
                }

                foreach (var character in word.Characters)
                {
                    // Character-level analysis
                    string charText = character.Text;
                    double charConfidence = character.Co/nfidence;

                    // Alternative character choices for spell-checking
                    OcrResult.Choice[] alternatives = character.Choices;
                }
            }
        }
    }
}
Imports System
Imports IronOcr
Imports IronSoftware.Drawing

' Configure with barcode support
Dim ocr As New IronTesseract With {
    .Configuration = New TesseractConfiguration With {
        .ReadBarCodes = True
    }
}

Using input As New OcrInput()

    ' Process multi-page document
    Dim pageIndices As Integer() = {1, 2}
    input.LoadImageFrames("img\Potter.tiff", pageIndices)

    Dim result As OcrResult = ocr.Read(input)

    ' Navigate the complete results hierarchy
    For Each page In result.Pages
        ' Page-level data
        Dim pageNumber As Integer = page.PageNumber
        Dim pageText As String = page.Text
        Dim pageWordCount As Integer = page.WordCount

        ' Extract page elements
        Dim barcodes As OcrResult.Barcode() = page.Barcodes
        Dim pageImage As AnyBitmap = page.ToBitmap()
        Dim pageWidth As Double = page.Width
        Dim pageHeight As Double = page.Height

        For Each paragraph In page.Paragraphs
            ' Paragraph properties
            Dim paragraphNumber As Integer = paragraph.ParagraphNumber
            Dim paragraphText As String = paragraph.Text
            Dim paragraphConfidence As Double = paragraph.Confidence
            Dim textDirection = paragraph.TextDirection

            For Each line In paragraph.Lines
                ' Line details including baseline information
                Dim lineText As String = line.Text
                Dim lineConfidence As Double = line.Confidence
                Dim baselineAngle As Double = line.BaselineAngle
                Dim baselineOffset As Double = line.BaselineOffset

                For Each word In line.Words
                    ' Word-level data
                    Dim wordText As String = word.Text
                    Dim wordConfidence As Double = word.Confidence

                    ' Font information (when available)
                    If word.Font IsNot Nothing Then
                        Dim fontName As String = word.Font.FontName
                        Dim fontSize As Double = word.Font.FontSize
                        Dim isBold As Boolean = word.Font.IsBold
                        Dim isItalic As Boolean = word.Font.IsItalic
                    End If

                    For Each character In word.Characters
                        ' Character-level analysis
                        Dim charText As String = character.Text
                        Dim charConfidence As Double = character.Confidence

                        ' Alternative character choices for spell-checking
                        Dim alternatives As OcrResult.Choice() = character.Choices
                    Next
                Next
            Next
        Next
    Next
End Using
$vbLabelText   $csharpLabel

摘要

IronOCR 為 C# 開發人員提供最先進的 Tesseract API 實作,可在 Windows、Linux 和 Mac 平台上無縫運行。 其透過 IronOCR 精準讀取圖像文字的能力——即使面對品質不佳的文件亦然——使其有別於基礎的 OCR 解決方案。

該函式庫的獨特功能包括整合式 BarCode 讀取,以及將結果匯出為可搜尋 PDF 或 HOCR HTML 的能力,這些功能在標準的 Tesseract 實作中並未提供。

後續進行

繼續掌握 IronOCR:

原始碼下載

準備好在您的應用程式中實作 C# OCR 圖像轉文字功能了嗎? 立即下載 IronOCR 並開始您的免費試用

常見問題

如何在不使用 Tesseract 的情況下,透過 C# 將圖片轉換為文字?

您可使用 IronOCR 在 C# 中將圖片轉換為文字,無需使用 Tesseract。IronOCR 透過內建方法直接處理圖像轉文字的轉換,使流程更加簡便。

如何提升低畫質圖片的 OCR 辨識準確度?

IronOCR 提供 Input.Deskew()Input.DeNoise() 等影像濾鏡,可用於透過校正傾斜和降低雜訊來增強低品質影像,從而顯著提升 OCR 準確度。

如何使用 C# 的 OCR 從多頁文件中擷取文字?

若要從多頁文件中擷取文字,IronOCR 允許您透過 LoadPdf() 等方法載入並處理 PDF 檔案,或處理 TIFF 檔案,將每頁內容有效轉換為文字。

是否可以同時從圖片中讀取BarCode和文字?

是的,IronOCR 能夠從單一影像中讀取文字和 BARCODE。您可以透過 OCR.Configuration.ReadBarCodes = true 啟用 BARCODE 讀取功能,這將允許同時擷取文字和 BARCODE 資料。

如何設定 OCR 來處理多語言文件?

IronOCR 支援超過 125 種語言,您可透過 OCR 設定主要語言,並使用 OCR.AddSecondaryLanguage() 新增其他語言,以進行多語言文件處理。

有哪些方法可用於將 OCR 結果匯出為不同格式?

IronOCR 提供多種輸出 OCR 結果的方法,例如用於 PDF 的 SaveAsSearchablePdf()、用於純文字的 SaveAsTextFile(),以及用於 HOCR HTML 格式的 SaveAsHocrFile()

如何優化大型圖像檔案的 OCR 處理速度?

為優化 OCR 處理速度,請使用 IronOCR 的 OcrLanguage.Fast 以加快語言辨識速度,並透過 System.Drawing.Rectangle 定義特定區域進行 OCR,以縮短處理時間。

如何處理受保護 PDF 檔案的 OCR 處理?

處理受保護的 PDF 檔案時,請使用 LoadPdf() 方法並輸入正確的密碼。IronOCR 會自動將基於影像的 PDF 頁面轉換為影像,以便進行 OCR 處理。

如果 OCR 結果不準確,我該怎麼辦?

若 OCR 結果不準確,請考慮使用 IronOCR 的影像增強功能(例如 Input.Deskew()Input.DeNoise()),並確保已安裝正確的語言套件。

我可以自訂 OCR 流程以排除特定字元嗎?

是的,IronOCR 允許透過 BlackListCharacters 屬性自訂 OCR 流程,以排除特定字元,藉此僅聚焦於相關文字,從而提升準確度與處理速度。

雅各·梅勒(Jacob Mellor),Team Iron 首席技術長
技術長

雅各·梅勒(Jacob Mellor)是 Iron Software 的首席技術官,也是一位開創 C# PDF 技術的遠見卓識工程師。作為 Iron Software 核心程式碼庫的原始開發者,他自公司成立以來便塑造了產品架構,並與執行長卡梅隆·里明頓(Cameron Rimington)共同將公司發展為擁有 50 多名員工的企業,服務對象包括 NASA、特斯拉(Tesla)及全球政府機構。

雅各布於曼徹斯特大學(1998–2001)取得土木工程一等榮譽工程學士學位(BEng)。他在 1999 年於倫敦創立首家軟體公司,並於 2005 年開發出首批 .NET 元件,此後專注於解決微軟生態系統中的複雜問題。

其旗艦產品 IronPDF 與 Iron Suite .NET 函式庫在全球已累積超過 3,000 萬次 NuGet 安裝,其基礎程式碼持續驅動著全球廣泛使用的開發者工具。憑藉 25 年商業經驗與 41 年程式設計專業,雅各持續致力於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領導者。

審閱者:
Jeff Fritz
Jeffrey T. Fritz
首席程式經理 - .NET 社群團隊
Jeff 同時也是 .NET 與 Visual Studio 團隊的首席程式經理。他是 .NET Conf 虛擬會議系列的執行製作人,並主持每週播出兩次的開發者直播節目《Fritz and Friends》,在節目中他會與觀眾一起探討技術話題並共同編寫程式碼。Jeff 負責撰寫工作坊內容、準備簡報,並為 Microsoft Build、Microsoft Ignite、.NET Conf 以及 Microsoft MVP Summit 等微軟最大規模的開發者活動規劃內容。
準備開始了嗎?
Nuget 下載 5,888,303 | 版本: 2026.5 just released
Still Scrolling Icon

還在往下捲動嗎?

想要快速確認成果嗎? PM > Install-Package IronOcr
執行範例 觀看您的圖片轉為可搜尋文字。