如何在C#中使用IronOCR讀取截圖
IronOCR 的 ReadScreenshot 方法可從各種尺寸、含有雜訊的截圖中有效擷取文字,並支援 PNG、JPG、BMP 等常見檔案格式。
螢幕截圖可快速分享資訊並擷取重要資料。不過,截圖的尺寸不一,也可能含有雜訊,因此較難透過 OCR 擷取文字。
IronOCR 提供 ReadScreenshot 等專用方法,針對截圖的讀取和資訊擷取做了最佳化,並支援常見檔案格式。這個方法有別於標準 OCR 方法,會針對截圖套用自動降噪、增強對比等前處理。
要使用此功能,請安裝 [IronOcr.Extension.AdvancedScan] 套件。 本擴充套件提供先進的電腦視覺功能,可提升螢幕截圖文字的辨識準確度,特別是針對現代應用程式中的 UI 元件、系統字型和反鋸齒文字。
使用 IronOCR 的 ReadScreenshot,只需幾秒就能開始。將截圖載入 OcrInput,呼叫 ReadScreenShot,即可從 OcrPhotoResult 取得擷取的文字、信心度分數及文字區域。只需少量設定,就能快速將影像轉換為可用的文字。
-
1使用 IronOCR 安裝 NuGet Package Manager
-
2複製並運行這段程式碼。
OcrPhotoResult result = new IronTesseract().ReadScreenShot(new OcrInput().LoadImage("screenshot.png"));Dim result As OcrPhotoResult = New IronTesseract().ReadScreenShot(New OcrInput().LoadImage("screenshot.png"))Dim result As OcrPhotoResult = New IronTesseract().ReadScreenShot(New OcrInput().LoadImage("screenshot.png")) -
3部署到您的生產環境進行測試
立即在您的項目中開始使用 IronOCR,並使用 免費試用
本指南透過程式碼範例和結果物件的屬性,示範如何使用 IronOCR 辨識螢幕截圖中的文字。也會介紹處理特定區域、辨識多語言內容及提升批次處理效能等進階用法。
基本工作流程(5 個步驟)
- 下載用於讀取截圖的 C# 程式庫
- 匯入要處理的螢幕截圖
- 使用
ReadScreenshot方法從影像中擷取文字 - 使用OcrPhotoResult屬性取得擷取的資料,供後續處理
- 根據需要儲存或匯出擷取的文字
如何使用 ReadScreenshot 擷取截圖文字?
在 IronOCR 中呼叫 ReadScreenshot 時,請傳入 OcrInput。相較於程式庫的標準 Read 方法,這個方法更適合處理截圖。它能自動偵測使用者介面元件,更妥善地處理反鋸齒字型,也能更準確地辨識不同作業系統的系統字型。
什麼類型的截圖效果最佳?
下方是程式碼範例使用的輸入影像,混合了不同字型和字級,藉此展示方法的適用範圍。ReadScreenshot 特別擅長辨識下列內容:
- 系統 UI 字型 (Windows, macOS, Linux)
- 來自現代應用程式的反鋸齒文字
- 混合字型大小和樣式
- 複雜背景上覆蓋的文字
- 主控台輸出和終端截圖
- 使用各種網頁字型的瀏覽器內容
為了取得最佳結果,請以原始解析度擷取截圖,避免壓縮。此方法支援多種影像格式,其中 PNG 採用無損壓縮,最能保留文字清晰度。

如何實作 ReadScreenshot 方法?
using IronOcr;
using System;
using System.Linq;
// Instantiate OCR engine
var ocr = new IronTesseract();
using var inputScreenshot = new OcrInput();
inputScreenshot.LoadImage("screenshotOCR.png");
// Perform OCR
OcrPhotoResult result = ocr.ReadScreenShot(inputScreenshot);
// Output screenshot information
Console.WriteLine(result.Text);
Console.WriteLine(result.TextRegions.First().Region.X);
Console.WriteLine(result.TextRegions.Last().Region.Width);
Console.WriteLine(result.Confidence);using IronOcr;
using System;
using System.Linq;
// Instantiate OCR engine
var ocr = new IronTesseract();
using var inputScreenshot = new OcrInput();
inputScreenshot.LoadImage("screenshotOCR.png");
// Perform OCR
OcrPhotoResult result = ocr.ReadScreenShot(inputScreenshot);
// Output screenshot information
Console.WriteLine(result.Text);
Console.WriteLine(result.TextRegions.First().Region.X);
Console.WriteLine(result.TextRegions.Last().Region.Width);
Console.WriteLine(result.Confidence);Imports IronOcr
Imports System
Imports System.Linq
' Instantiate OCR engine
Dim ocr = New IronTesseract()
Using inputScreenshot = New OcrInput()
inputScreenshot.LoadImage("screenshotOCR.png")
' Perform OCR
Dim result As OcrPhotoResult = ocr.ReadScreenShot(inputScreenshot)
' Output screenshot information
Console.WriteLine(result.Text)
Console.WriteLine(result.TextRegions.First().Region.X)
Console.WriteLine(result.TextRegions.Last().Region.Width)
Console.WriteLine(result.Confidence)
End UsingImports IronOcr
Imports System
Imports System.Linq
' Instantiate OCR engine
Dim ocr = New IronTesseract()
Using inputScreenshot = New OcrInput()
inputScreenshot.LoadImage("screenshotOCR.png")
' Perform OCR
Dim result As OcrPhotoResult = ocr.ReadScreenShot(inputScreenshot)
' Output screenshot information
Console.WriteLine(result.Text)
Console.WriteLine(result.TextRegions.First().Region.X)
Console.WriteLine(result.TextRegions.Last().Region.Width)
Console.WriteLine(result.Confidence)
End Using遇到較複雜的截圖時,可加入下列前處理步驟以改善辨識效果:
using IronOcr;
using System;
// Configure OCR engine with specific settings for screenshots
var ocr = new IronTesseract()
{
// Set language for better accuracy with non-English content
Language = OcrLanguage.English,
// Configure for screen-resolution images
Configuration = new TesseractConfiguration()
{
PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd,
// Enable whitelist for specific characters if needed
WhiteListCharacters = null
}
};
using var inputScreenshot = new OcrInput();
// Load screenshot with specific DPI setting for consistency
inputScreenshot.LoadImage("screenshotOCR.png");
// Apply preprocessing for better accuracy
inputScreenshot.DeNoise(); // Remove screenshot artifacts
inputScreenshot.Sharpen(); // Enhance text edges
// Perform OCR with error handling
try
{
OcrPhotoResult result = ocr.ReadScreenShot(inputScreenshot);
// Process results with confidence threshold
if (result.Confidence > 0.8)
{
Console.WriteLine($"High confidence text extraction: {result.Text}");
}
else
{
Console.WriteLine("Low confidence - consider image preprocessing");
}
}
catch (Exception ex)
{
Console.WriteLine($"OCR Error: {ex.Message}");
}using IronOcr;
using System;
// Configure OCR engine with specific settings for screenshots
var ocr = new IronTesseract()
{
// Set language for better accuracy with non-English content
Language = OcrLanguage.English,
// Configure for screen-resolution images
Configuration = new TesseractConfiguration()
{
PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd,
// Enable whitelist for specific characters if needed
WhiteListCharacters = null
}
};
using var inputScreenshot = new OcrInput();
// Load screenshot with specific DPI setting for consistency
inputScreenshot.LoadImage("screenshotOCR.png");
// Apply preprocessing for better accuracy
inputScreenshot.DeNoise(); // Remove screenshot artifacts
inputScreenshot.Sharpen(); // Enhance text edges
// Perform OCR with error handling
try
{
OcrPhotoResult result = ocr.ReadScreenShot(inputScreenshot);
// Process results with confidence threshold
if (result.Confidence > 0.8)
{
Console.WriteLine($"High confidence text extraction: {result.Text}");
}
else
{
Console.WriteLine("Low confidence - consider image preprocessing");
}
}
catch (Exception ex)
{
Console.WriteLine($"OCR Error: {ex.Message}");
}Imports IronOcr
Imports System
' Configure OCR engine with specific settings for screenshots
Dim ocr As New IronTesseract() With {
' Set language for better accuracy with non-English content
.Language = OcrLanguage.English,
' Configure for screen-resolution images
.Configuration = New TesseractConfiguration() With {
.PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd,
' Enable whitelist for specific characters if needed
.WhiteListCharacters = Nothing
}
}
Using inputScreenshot As New OcrInput()
' Load screenshot with specific DPI setting for consistency
inputScreenshot.LoadImage("screenshotOCR.png")
' Apply preprocessing for better accuracy
inputScreenshot.DeNoise() ' Remove screenshot artifacts
inputScreenshot.Sharpen() ' Enhance text edges
' Perform OCR with error handling
Try
Dim result As OcrPhotoResult = ocr.ReadScreenShot(inputScreenshot)
' Process results with confidence threshold
If result.Confidence > 0.8 Then
Console.WriteLine($"High confidence text extraction: {result.Text}")
Else
Console.WriteLine("Low confidence - consider image preprocessing")
End If
Catch ex As Exception
Console.WriteLine($"OCR Error: {ex.Message}")
End Try
End UsingImports IronOcr
Imports System
' Configure OCR engine with specific settings for screenshots
Dim ocr As New IronTesseract() With {
' Set language for better accuracy with non-English content
.Language = OcrLanguage.English,
' Configure for screen-resolution images
.Configuration = New TesseractConfiguration() With {
.PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd,
' Enable whitelist for specific characters if needed
.WhiteListCharacters = Nothing
}
}
Using inputScreenshot As New OcrInput()
' Load screenshot with specific DPI setting for consistency
inputScreenshot.LoadImage("screenshotOCR.png")
' Apply preprocessing for better accuracy
inputScreenshot.DeNoise() ' Remove screenshot artifacts
inputScreenshot.Sharpen() ' Enhance text edges
' Perform OCR with error handling
Try
Dim result As OcrPhotoResult = ocr.ReadScreenShot(inputScreenshot)
' Process results with confidence threshold
If result.Confidence > 0.8 Then
Console.WriteLine($"High confidence text extraction: {result.Text}")
Else
Console.WriteLine("Low confidence - consider image preprocessing")
End If
Catch ex As Exception
Console.WriteLine($"OCR Error: {ex.Message}")
End Try
End UsingOcrPhotoResult 提供哪些屬性?

主控台會輸出從截圖中擷取的所有文字。以下介紹 OcrPhotoResult 的屬性及其用法:
Text: 從 OCR 輸入中擷取的文字。 此屬性包含以單一字串形式呈現的所有辨識文字,並保留原始版面的換行與間距。Confidence: 表示統計辨識信心度的雙精確度屬性,範圍為 0 到 1,1 代表最高信心度。您可以用此值在應用程式中實作品質控管。TextRegion: 由TextRegion物件組成的陣列,其屬性指出截圖中辨識到文字的區域。依預設,每個TextRegion都是 IronOCR 模型中衍生自Rectangle的類別,包含矩形的x、y座標及height、width。
使用 TextRegions 可以讓您:
- 從特定的螢幕截圖區域擷取文字
- 找出 UI 元件的位置
- 根據文字位置建立可點選的覆蓋圖
- 實作特定區域的 OCR 處理
以下是處理個別文字區域的範例:
using IronOcr;
using System;
using System.Linq;
var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage("screenshot.png");
OcrPhotoResult result = ocr.ReadScreenShot(input);
// Process each text region individually
foreach (var region in result.TextRegions)
{
Console.WriteLine($"Text: {region.TextInRegion}");
Console.WriteLine($"Location: X={region.Region.X}, Y={region.Region.Y}");
Console.WriteLine($"Size: {region.Region.Width}x{region.Region.Height}");
Console.WriteLine($"Confidence: {region.RegionConf:P2}");
Console.WriteLine("---");
}
// Find specific UI elements by text content
var buttonRegion = result.TextRegions
.FirstOrDefault(r => r.TextInRegion.Contains("Submit", StringComparison.OrdinalIgnoreCase));
if (buttonRegion != null)
{
Console.WriteLine($"Found button at: {buttonRegion.Region.X}, {buttonRegion.Region.Y}");
}using IronOcr;
using System;
using System.Linq;
var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage("screenshot.png");
OcrPhotoResult result = ocr.ReadScreenShot(input);
// Process each text region individually
foreach (var region in result.TextRegions)
{
Console.WriteLine($"Text: {region.TextInRegion}");
Console.WriteLine($"Location: X={region.Region.X}, Y={region.Region.Y}");
Console.WriteLine($"Size: {region.Region.Width}x{region.Region.Height}");
Console.WriteLine($"Confidence: {region.RegionConf:P2}");
Console.WriteLine("---");
}
// Find specific UI elements by text content
var buttonRegion = result.TextRegions
.FirstOrDefault(r => r.TextInRegion.Contains("Submit", StringComparison.OrdinalIgnoreCase));
if (buttonRegion != null)
{
Console.WriteLine($"Found button at: {buttonRegion.Region.X}, {buttonRegion.Region.Y}");
}Imports IronOcr
Imports System
Imports System.Linq
Dim ocr = New IronTesseract()
Using input = New OcrInput()
input.LoadImage("screenshot.png")
Dim result As OcrPhotoResult = ocr.ReadScreenShot(input)
' Process each text region individually
For Each region In result.TextRegions
Console.WriteLine($"Text: {region.TextInRegion}")
Console.WriteLine($"Location: X={region.Region.X}, Y={region.Region.Y}")
Console.WriteLine($"Size: {region.Region.Width}x{region.Region.Height}")
Console.WriteLine($"Confidence: {region.RegionConf:P2}")
Console.WriteLine("---")
Next
' Find specific UI elements by text content
Dim buttonRegion = result.TextRegions _
.FirstOrDefault(Function(r) r.TextInRegion.Contains("Submit", StringComparison.OrdinalIgnoreCase))
If buttonRegion IsNot Nothing Then
Console.WriteLine($"Found button at: {buttonRegion.Region.X}, {buttonRegion.Region.Y}")
End If
End UsingImports IronOcr
Imports System
Imports System.Linq
Dim ocr = New IronTesseract()
Using input = New OcrInput()
input.LoadImage("screenshot.png")
Dim result As OcrPhotoResult = ocr.ReadScreenShot(input)
' Process each text region individually
For Each region In result.TextRegions
Console.WriteLine($"Text: {region.TextInRegion}")
Console.WriteLine($"Location: X={region.Region.X}, Y={region.Region.Y}")
Console.WriteLine($"Size: {region.Region.Width}x{region.Region.Height}")
Console.WriteLine($"Confidence: {region.RegionConf:P2}")
Console.WriteLine("---")
Next
' Find specific UI elements by text content
Dim buttonRegion = result.TextRegions _
.FirstOrDefault(Function(r) r.TextInRegion.Contains("Submit", StringComparison.OrdinalIgnoreCase))
If buttonRegion IsNot Nothing Then
Console.WriteLine($"Found button at: {buttonRegion.Region.X}, {buttonRegion.Region.Y}")
End If
End Using進階截圖處理技術
處理多語言截圖
IronOCR 提供可靠的多語言支援,適合處理國際化應用程式或多語言使用者介面的截圖:
using IronOcr;
// Configure for multiple languages
var ocr = new IronTesseract();
ocr.AddSecondaryLanguage(OcrLanguage.ChineseSimplified);
ocr.AddSecondaryLanguage(OcrLanguage.Japanese);
using var input = new OcrInput();
input.LoadImage("multilingual-screenshot.png");
// Process with language detection
OcrPhotoResult result = ocr.ReadScreenShot(input);
Console.WriteLine($"Extracted multilingual text: {result.Text}");using IronOcr;
// Configure for multiple languages
var ocr = new IronTesseract();
ocr.AddSecondaryLanguage(OcrLanguage.ChineseSimplified);
ocr.AddSecondaryLanguage(OcrLanguage.Japanese);
using var input = new OcrInput();
input.LoadImage("multilingual-screenshot.png");
// Process with language detection
OcrPhotoResult result = ocr.ReadScreenShot(input);
Console.WriteLine($"Extracted multilingual text: {result.Text}");Imports IronOcr
' Configure for multiple languages
Dim ocr As New IronTesseract()
ocr.AddSecondaryLanguage(OcrLanguage.ChineseSimplified)
ocr.AddSecondaryLanguage(OcrLanguage.Japanese)
Using input As New OcrInput()
input.LoadImage("multilingual-screenshot.png")
' Process with language detection
Dim result As OcrPhotoResult = ocr.ReadScreenShot(input)
Console.WriteLine($"Extracted multilingual text: {result.Text}")
End UsingImports IronOcr
' Configure for multiple languages
Dim ocr As New IronTesseract()
ocr.AddSecondaryLanguage(OcrLanguage.ChineseSimplified)
ocr.AddSecondaryLanguage(OcrLanguage.Japanese)
Using input As New OcrInput()
input.LoadImage("multilingual-screenshot.png")
' Process with language detection
Dim result As OcrPhotoResult = ocr.ReadScreenShot(input)
Console.WriteLine($"Extracted multilingual text: {result.Text}")
End Using批次處理的效能最佳化
在處理多個螢幕截圖時,請執行這些最佳化策略:
using IronOcr;
using System.Collections.Generic;
using System.Threading.Tasks;
public async Task ProcessScreenshotBatchAsync(List<string> screenshotPaths)
{
var ocr = new IronTesseract();
// Process screenshots in parallel for better performance
var tasks = screenshotPaths.Select(async path =>
{
using var input = new OcrInput();
input.LoadImage(path);
// Apply consistent preprocessing
input.DeNoise();
var result = await Task.Run(() => ocr.ReadScreenShot(input));
return new { Path = path, Result = result };
});
var results = await Task.WhenAll(tasks);
// Process results
foreach (var item in results)
{
Console.WriteLine($"File: {item.Path}");
Console.WriteLine($"Text: {item.Result.Text}");
Console.WriteLine($"Confidence: {item.Result.Confidence:P2}");
}
}using IronOcr;
using System.Collections.Generic;
using System.Threading.Tasks;
public async Task ProcessScreenshotBatchAsync(List<string> screenshotPaths)
{
var ocr = new IronTesseract();
// Process screenshots in parallel for better performance
var tasks = screenshotPaths.Select(async path =>
{
using var input = new OcrInput();
input.LoadImage(path);
// Apply consistent preprocessing
input.DeNoise();
var result = await Task.Run(() => ocr.ReadScreenShot(input));
return new { Path = path, Result = result };
});
var results = await Task.WhenAll(tasks);
// Process results
foreach (var item in results)
{
Console.WriteLine($"File: {item.Path}");
Console.WriteLine($"Text: {item.Result.Text}");
Console.WriteLine($"Confidence: {item.Result.Confidence:P2}");
}
}Imports IronOcr
Imports System.Collections.Generic
Imports System.Threading.Tasks
Public Async Function ProcessScreenshotBatchAsync(screenshotPaths As List(Of String)) As Task
Dim ocr = New IronTesseract()
' Process screenshots in parallel for better performance
Dim tasks = screenshotPaths.Select(Async Function(path)
Using input = New OcrInput()
input.LoadImage(path)
' Apply consistent preprocessing
input.DeNoise()
Dim result = Await Task.Run(Function() ocr.ReadScreenShot(input))
Return New With {Key .Path = path, Key .Result = result}
End Using
End Function)
Dim results = Await Task.WhenAll(tasks)
' Process results
For Each item In results
Console.WriteLine($"File: {item.Path}")
Console.WriteLine($"Text: {item.Result.Text}")
Console.WriteLine($"Confidence: {item.Result.Confidence:P2}")
Next
End FunctionImports IronOcr
Imports System.Collections.Generic
Imports System.Threading.Tasks
Public Async Function ProcessScreenshotBatchAsync(screenshotPaths As List(Of String)) As Task
Dim ocr = New IronTesseract()
' Process screenshots in parallel for better performance
Dim tasks = screenshotPaths.Select(Async Function(path)
Using input = New OcrInput()
input.LoadImage(path)
' Apply consistent preprocessing
input.DeNoise()
Dim result = Await Task.Run(Function() ocr.ReadScreenShot(input))
Return New With {Key .Path = path, Key .Result = result}
End Using
End Function)
Dim results = Await Task.WhenAll(tasks)
' Process results
For Each item In results
Console.WriteLine($"File: {item.Path}")
Console.WriteLine($"Text: {item.Result.Text}")
Console.WriteLine($"Confidence: {item.Result.Confidence:P2}")
Next
End Function截圖 OCR 的最佳做法
- 擷取品質: 以原始解析度擷取截圖,避免縮放
- 格式選擇: 使用 PNG 格式,透過無損壓縮保留畫質
- 前處理: 依截圖內容套用適當的濾鏡
- 信心度門檻: 在關鍵應用中根據辨識信心度進行驗證
- 進度追蹤: 為耗時作業實作進度追蹤
常見使用情境
ReadScreenshot 方法適合於:
- 自動化 UI 測試與驗證
- 數位資產管理系統
- 擷取錯誤訊息的客戶支援工具
- 文件自動化
- 為螢幕助讀程式提供的輔助工具
- 遊戲與串流應用程式
與IronOCR功能的整合
截圖讀取功能可與其他 IronOCR 功能整合。您可以透過操作 OCR 結果以多種格式匯出資料,或使用進階 Tesseract 設定微調辨識準確度。
總結
IronOCR 的 ReadScreenshot 方法專為擷取截圖文字而最佳化。它透過專用前處理提供準確的辨識和完整的結果資料,協助開發人員建立能可靠處理截圖內容的應用程式。無論是自動化工具、無障礙解決方案或資料擷取系統,ReadScreenshot 都具備正式環境所需的效能和準確度。
常見問題
使用IronOCR的`ReadScreenshot`方法的主要優勢是什麼?
IronOCR的ReadScreenshot方法經過優化,可從截圖中讀取文字,提供自動降噪和UI元素檢測等功能,提高文字識別準確性。
IronOCR的`ReadScreenshot`方法支持哪些圖像格式?
IronOCR的ReadScreenshot方法支持常見的文件格式,如PNG、JPG和BMP,使其能處理各種類型的截圖。
IronOCR如何處理截圖中的不同文字字體和大小?
IronOCR的ReadScreenshot方法在識別系統UI字體、抗鋸齒文字和混合字體大小方面表現出色,甚至可以在複雜背景上準確提取文字。
IronOCR的`ReadScreenshot`方法可以處理多語言截圖嗎?
是的,IronOCR提供可靠的多語言文字識別支援,對含有多個國際語言的截圖非常有效。
IronOCR使用哪些預處理技術來提升截圖的文字提取?
IronOCR使用如降噪和對比度增強等預處理技術來提高截圖中文字提取的準確性。
如何安裝使用IronOCR的`ReadScreenshot`方法所需的工具?
要使用ReadScreenshot功能,從NuGet安裝IronOcr程式庫以及可選的IronOcr.Extension.AdvancedScan套件以獲得進階截圖文字識別功能。
`OcrPhotoResult`在使用`ReadScreenshot`方法時返回哪些屬性?
OcrPhotoResult返回提取的文字、可信度分數和文字區域等屬性,提供關於已識別文字及其在截圖中的位置的詳細信息。
IronOCR如何確保從截圖中提取文字的高準確性?
IronOCR通過應用自動檢測抗鋸齒和UI字體等多項優化,以及針對截圖特定挑戰的、高級預處理確保高準確性。
使用IronOCR時,PNG是截圖的最佳格式嗎?
是的,建議使用PNG格式的截圖,因為它可保存最佳的文本清晰度,由於無損壓縮,從而導致更準確的OCR結果。
IronOCR的`ReadScreenshot`方法有哪些常見應用場景?
ReadScreenshot方法的常見應用場景包括自動化UI測試、數位資產管理、客戶支援工具、文檔自動化和螢幕閱讀器的無障礙工具。
Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。