How to Read QR Codes from Images in C

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

IronQR 讓開發人員能夠透過 C# 從各種圖像格式讀取 QR 碼,方法是載入圖像並使用 IronDrawing,建立 QrImageInput 物件,並運用 BarcodeReader.Read 方法高效解碼 QR 資料。

快速入門:使用 C# 從圖片讀取 QR 碼

如何讀取不同圖像格式的 QR 碼?

IronQR 內建支援從各種圖像格式讀取 QR 碼。 此功能採用先進的機器學習模型,以確保在不同媒體類型間進行精確解碼。支援的格式包括:

  • 聯合影像專家小組 (JPEG)
  • 可攜式網路圖形 (PNG)
  • 圖形交換格式 (GIF)
  • 標記圖像檔案格式 (TIFF)
  • 位圖影像檔案 (BMP)
  • WBMP
  • WebP
  • 圖示 (ico)
  • WMF
  • RawFormat (原始碼)

此格式支援功能由開源函式庫 IronDrawing 提供,該函式庫能高效處理影像處理作業。 您可以處理來自數位相機、掃描器、行動裝置或網路下載的 QR 碼,無需進行格式轉換。

帶有清晰黑白圖案的示範 QR 碼,顯示定位方塊及用於測試影像掃描的資料模組
  1. using NuGet 套件管理員安裝 https://www.nuget.org/packages/IronQR

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

    // Import necessary IronQR and IronDrawing namespaces
    using IronSoftware.Drawing; 
    using IronBarcode;
    
    public class QRCodeReader
    {
        public static void Main()
        {
            // Load an image from a file path
            using (var inputImage = Image.FromFile("path/to/your/image/file.webp"))
            {
                // Create a QrImageInput object from the image
                var qrImageInput = new QrImageInput(inputImage);
    
                // Decode the QR 碼 from the image
                var result = BarcodeReader.Read(qrImageInput);
    
                // Iterate through each detected QR 碼 and display its information
                foreach (var barcodeResult in result.Barcodes)
                {
                    Console.WriteLine($"QR Code Data: {barcodeResult.Value}");
                }
            }
        }
    }
  3. 部署至您的生產環境進行測試

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

    arrow pointer

注意:請將"path/to/your/image/file.webp"替換為您 QR 碼圖片檔案的實際路徑。

對範例圖片中的 QR 碼內容感到好奇嗎?試著使用程式碼片段來體驗看看吧!

為什麼 IronQR 支援多種圖像格式?

讀取 QR 碼是指掃描並解碼 QR 碼中所儲存的資訊。 這通常是透過相機或掃描器,搭配能夠解讀 QR 碼資料的軟體來實現。 QR 碼中的資訊可以是文字、網址、聯絡資訊或其他形式的数据。

IronQR 的多格式支援對於實際應用至關重要,因為 QR 碼會出現在各種情境中——從行銷材料和產品包裝,到數位文件和網頁內容。 透過支援多種格式,IronQR 確保開發人員能夠建立穩健的應用程式,無需擔心圖像格式的相容性問題。 進一步了解 IronQR 的讀取功能,瞭解這種靈活性如何提升您的開發工作流程。

何時該使用哪種圖像格式?

在 QR 碼處理中,不同的圖像格式各有其用途:

  • PNG:最適合需要透明背景的 QR 碼,或當影像品質至關重要時。 PNG 的無損壓縮技術可確保 QR 碼圖案保持清晰且可讀。
  • JPEG:適用於包含 QR 碼的照片,或當檔案大小是考量因素時。 請使用較高的品質設定(80% 以上),以避免壓縮失真影響可讀性。
  • TIFF:非常適合用於歸檔,或在Enterprise環境中處理掃描文件。
  • WebP:一種現代格式,具備出色的壓縮效果且能保留畫質,非常適合用於網路應用程式。

無論採用何種格式,為獲得最佳效果,請確保圖片具備足夠的解析度(PRINT 用 QR 碼至少需 300 DPI)與對比度。請參閱我們的高階 QR 碼讀取範例,了解針對特定格式的最佳化技巧。

若影像品質不佳會如何?

IronQR 整合了容錯功能,以處理畫質不佳的圖像。 在處理畫質不佳的圖片時,該函式庫會採用幾種策略:

  1. 錯誤校正:QR 碼具備錯誤校正功能(L、M、Q、H 等級),即使條碼有高達 30% 的區域受損,仍可進行資料復原。
  2. 機器學習增強功能:IronQR 的機器學習模型可偵測並修正常見問題,例如模糊、變形及光線不足。
  3. 預處理:自動影像增強功能會在進行解碼嘗試前,先提升對比度與清晰度。

面對複雜情境時,請考慮使用自訂 QR 讀取模式選項來微調讀取流程:

// Example: Reading QR 碼s with enhanced error correction
using IronBarcode;

public class EnhancedQRReader
{
    public static void ReadPoorQualityImage()
    {
        // Configure reader with multiple attempts and error correction
        var options = new BarcodeReaderOptions
        {
            Speed = ReadingSpeed.Detailed, // More thorough scanning
            ExpectMultipleBarcodes = true,  // Check for multiple codes
            ExpectBarcodeTypes = BarcodeType.QRCode // Focus on QR 碼s only
        };

        using (var inputImage = Image.FromFile("blurry_qr_code.jpg"))
        {
            var qrImageInput = new QrImageInput(inputImage);
            var results = BarcodeReader.Read(qrImageInput, options);

            foreach (var result in results.Barcodes)
            {
                Console.WriteLine($"Decoded: {result.Value}");
                Console.WriteLine($"Confidence: {result.Co/nfidence}%");
            }
        }
    }
}
// Example: Reading QR 碼s with enhanced error correction
using IronBarcode;

public class EnhancedQRReader
{
    public static void ReadPoorQualityImage()
    {
        // Configure reader with multiple attempts and error correction
        var options = new BarcodeReaderOptions
        {
            Speed = ReadingSpeed.Detailed, // More thorough scanning
            ExpectMultipleBarcodes = true,  // Check for multiple codes
            ExpectBarcodeTypes = BarcodeType.QRCode // Focus on QR 碼s only
        };

        using (var inputImage = Image.FromFile("blurry_qr_code.jpg"))
        {
            var qrImageInput = new QrImageInput(inputImage);
            var results = BarcodeReader.Read(qrImageInput, options);

            foreach (var result in results.Barcodes)
            {
                Console.WriteLine($"Decoded: {result.Value}");
                Console.WriteLine($"Confidence: {result.Co/nfidence}%");
            }
        }
    }
}
Imports IronBarcode

Public Class EnhancedQRReader
    Public Shared Sub ReadPoorQualityImage()
        ' Configure reader with multiple attempts and error correction
        Dim options As New BarcodeReaderOptions With {
            .Speed = ReadingSpeed.Detailed, ' More thorough scanning
            .ExpectMultipleBarcodes = True, ' Check for multiple codes
            .ExpectBarcodeTypes = BarcodeType.QRCode ' Focus on QR 碼s only
        }

        Using inputImage = Image.FromFile("blurry_qr_code.jpg")
            Dim qrImageInput As New QrImageInput(inputImage)
            Dim results = BarcodeReader.Read(qrImageInput, options)

            For Each result In results.Barcodes
                Console.WriteLine($"Decoded: {result.Value}")
                Console.WriteLine($"Confidence: {result.Confidence}%")
            Next
        End Using
    End Sub
End Class
$vbLabelText   $csharpLabel

從 QR 碼擷取值

[//]: # (此為將被隱藏的註解。 "價值"一詞已在上述範例中提及。 (我將在重新定義時採取更具說明性但簡潔的表述方式)

IronQR 的大多數函式會傳回一個集合,以支援多重偵測。 由於 results 是一組物件序列,因此它本身並不具備 Value 屬性。 範例程式碼會從集合中特別選取第一個 QrResult,並擷取其 Value

:path=/static-assets/qr/content-code-examples/how-to/read-qr-code-image-value.cs
using System;
using System.Collections.Generic;
using System.Linq;
using IronQr;
using System.Drawing;

// Import image
var inputImage = Image.FromFile("sample.jpg");

// Load the asset into QrImageInput
QrImageInput imageInput = new QrImageInput(inputImage);

// Create a QR Reader object
QrReader reader = new QrReader();

// Read the Input an get all embedded QR Codes
IEnumerable<QrResult> results = reader.Read(imageInput);

// Display the value of the first QR code found
Console.WriteLine($"QR code value is {results.First().Value}");
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports IronQr
Imports System.Drawing

' Import image
Dim inputImage As Image = Image.FromFile("sample.jpg")

' Load the asset into QrImageInput
Dim imageInput As New QrImageInput(inputImage)

' Create a QR Reader object
Dim reader As New QrReader()

' Read the Input and get all embedded QR Codes
Dim results As IEnumerable(Of QrResult) = reader.Read(imageInput)

' Display the value of the first QR code found
Console.WriteLine($"QR code value is {results.First().Value}")
$vbLabelText   $csharpLabel

偵測圖片中的 QR 碼位置

IronQR 不僅能進行簡單的解碼,更能精確定位 QR 碼在圖片中的位置。 此定位採用標準座標系統,其中 PointF (0,0) 代表圖像的左上角。 QR 碼各角的精確空間座標可透過 Points[] 陣列取得。

在此範例中,系統會擷取偵測到的 QR 碼所有四個點的座標,並將其 PRINT 至控制台。

請注意此函式所回傳的座標以嚴格的"之字形"順序儲存:左上、右上、左下,最後是右下

:path=/static-assets/qr/content-code-examples/how-to/read-qr-code-image-position.cs
using System;
using System.Collections.Generic;
using IronQr;
using System.Drawing;
using System.Linq;

// Import an image containing a QR code
var inputImage = Image.FromFile("urlQr.png");

// Load the asset into a QrImageInput object
var imageInput = new QrImageInput(inputImage);

// Create a QR Reader object
var reader = new QrReader();

// Read the input and get all embedded QR codes
IEnumerable<QrResult> results = reader.Read(imageInput);

// [TL, TR, BL, BR]
string[] labels = { "Top-Left", "Top-Right", "Bottom-Left", "Bottom-Right" };

var points = results.First().Points;

for (int i = 0; i < points.Length; i++)
{
    Console.WriteLine($"{labels[i]}: {points[i].X}, {points[i].Y}");
}
Imports System
Imports System.Collections.Generic
Imports IronQr
Imports System.Drawing
Imports System.Linq

' Import an image containing a QR code
Dim inputImage As Image = Image.FromFile("urlQr.png")

' Load the asset into a QrImageInput object
Dim imageInput As New QrImageInput(inputImage)

' Create a QR Reader object
Dim reader As New QrReader()

' Read the input and get all embedded QR codes
Dim results As IEnumerable(Of QrResult) = reader.Read(imageInput)

' [TL, TR, BL, BR]
Dim labels As String() = { "Top-Left", "Top-Right", "Bottom-Left", "Bottom-Right" }

Dim points = results.First().Points

For i As Integer = 0 To points.Length - 1
    Console.WriteLine($"{labels(i)}: {points(i).X}, {points(i).Y}")
Next
$vbLabelText   $csharpLabel

輸入 QR 碼

QR 碼

輸出

請注意,系統已將每個 QR 碼角落的精確空間座標記錄至控制台。

邊緣偵測 QR

支援的 QR 碼類型

支援多種 QR 碼的建立與讀取。 IronQR 提供對各種 QR 碼格式的全面支援,以滿足多元的應用需求。 請參閱我們的文件,進一步了解支援的 QR 格式。 以下是支援的 QR 碼類型:

  • QRCode:當今最常用的標準 QR 碼。 它最多可儲存 7,089 個數字字元或 4,296 個字母數字字元,因此適用於網站網址、聯絡資訊及其他應用情境。
帶有清晰黑白圖案的示範 QR 碼,顯示定位方塊及用於測試影像掃描的資料模組
  • MicroQRCode:專為有限空間設計的標準 QR 碼縮小版。 最多可儲存 35 個數字或 21 個字母數字,非常適合小型包裝或微型印刷標籤。
帶有定位圖案和數據模組的標準 QR 碼,展示典型的 QR 碼結構
  • RMQRCode:RMQR 碼(矩形微型 QR 碼)是一種緊湊的矩形版本,而非正方形。 此版本支援靈活調整長寬比,適用於具備矩形空間的應用場景。
矩形 QR 碼範例,展示非正方形格式,並包含標準定位標記與資料圖案

如何選擇合適的 QR 碼類型?

選擇合適的 QR 碼類型取決於您的具體使用情境與限制條件:

  • 標準 QR 碼:適用於空間不受限且需要最大資料容量的通用應用場景。 非常適合用於 URL、Wi-Fi 憑證、vCard 聯絡人或詳細的產品資訊。 請參閱我們的 QR 碼生成範例以了解實作細節。

  • 微型 QR 碼:適用於電子元件、珠寶標籤或醫療設備等小面積表面。 儘管處理能力有限,但它非常適合用於序列號、簡單的 URL 或基礎追蹤代碼。

  • RMQR 條碼:當可用空間有特定尺寸限制時(例如圓柱形產品的狹窄標籤或包裝邊緣的狹長區域),請選擇矩形條碼。

資料儲存的限制有哪些?

了解資料容量有助於優化您的 QR 碼實作:

QR 碼類型 僅限數字 字母數字 二進位 漢字
標準 QR 7,089 4,296 2,953 1,817
Micro QR 35 21 15 9
RMQR 變數 變數 變數 變數

規劃資料儲存時,請考量以下因素:

  • 針對網頁連結使用網址縮短服務,以最大化可用空間
  • 針對大型資料集實作資料壓縮
  • 選擇適當的錯誤修正等級(較高的修正等級會降低處理能力)

若需進階實作,請參閱我們的"風格化 QR 碼生成指南",以在美觀性與資料容量之間取得平衡。

何時該使用微型條碼或 RMQR 條碼?

微型條碼與 RMQR 條碼在特定情境下表現尤為出色:

微型 QR 碼非常適合用於:

  • 需要元件追蹤功能的電子電路板
  • 需要患者或藥物識別碼的小型醫療設備
  • 鐫刻空間有限的珠寶鑑定
  • 製造業中的微型產品標籤

RMQR 條碼最適合用於:

  • 適用於管線或管道的窄版運送標籤
  • 筆桿或工具上的加長空格
  • 橫幅式行銷素材
  • 整合至現有的矩形設計元素中

以下是一個讀取不同類型 QR 碼的實用範例:

using IronBarcode;
using IronSoftware.Drawing;

public class MultiTypeQRReader
{
    public static void ReadVariousQRTypes()
    {
        // Configure reader to handle all QR 碼 types
        var options = new BarcodeReaderOptions
        {
            ExpectBarcodeTypes = BarcodeType.QRCode | 
                                BarcodeType.MicroQRCode | 
                                BarcodeType.RectangularMicroQRCode
        };

        string[] imagePaths = {
            "standard_qr.png",
            "micro_qr.png", 
            "rectangular_qr.png"
        };

        foreach (var path in imagePaths)
        {
            using (var image = Image.FromFile(path))
            {
                var qrInput = new QrImageInput(image);
                var results = BarcodeReader.Read(qrInput, options);

                foreach (var qr in results.Barcodes)
                {
                    Console.WriteLine($"Type: {qr.BarcodeType}");
                    Console.WriteLine($"Data: {qr.Value}");
                    Console.WriteLine($"Format: {qr.Format}");
                    Console.WriteLine("---");
                }
            }
        }
    }
}
using IronBarcode;
using IronSoftware.Drawing;

public class MultiTypeQRReader
{
    public static void ReadVariousQRTypes()
    {
        // Configure reader to handle all QR 碼 types
        var options = new BarcodeReaderOptions
        {
            ExpectBarcodeTypes = BarcodeType.QRCode | 
                                BarcodeType.MicroQRCode | 
                                BarcodeType.RectangularMicroQRCode
        };

        string[] imagePaths = {
            "standard_qr.png",
            "micro_qr.png", 
            "rectangular_qr.png"
        };

        foreach (var path in imagePaths)
        {
            using (var image = Image.FromFile(path))
            {
                var qrInput = new QrImageInput(image);
                var results = BarcodeReader.Read(qrInput, options);

                foreach (var qr in results.Barcodes)
                {
                    Console.WriteLine($"Type: {qr.BarcodeType}");
                    Console.WriteLine($"Data: {qr.Value}");
                    Console.WriteLine($"Format: {qr.Format}");
                    Console.WriteLine("---");
                }
            }
        }
    }
}
Imports IronBarcode
Imports IronSoftware.Drawing

Public Class MultiTypeQRReader
    Public Shared Sub ReadVariousQRTypes()
        ' Configure reader to handle all QR 碼 types
        Dim options As New BarcodeReaderOptions With {
            .ExpectBarcodeTypes = BarcodeType.QRCode Or
                                  BarcodeType.MicroQRCode Or
                                  BarcodeType.RectangularMicroQRCode
        }

        Dim imagePaths As String() = {
            "standard_qr.png",
            "micro_qr.png",
            "rectangular_qr.png"
        }

        For Each path In imagePaths
            Using image = Image.FromFile(path)
                Dim qrInput As New QrImageInput(image)
                Dim results = BarcodeReader.Read(qrInput, options)

                For Each qr In results.Barcodes
                    Console.WriteLine($"Type: {qr.BarcodeType}")
                    Console.WriteLine($"Data: {qr.Value}")
                    Console.WriteLine($"Format: {qr.Format}")
                    Console.WriteLine("---")
                Next
            End Using
        Next
    End Sub
End Class
$vbLabelText   $csharpLabel

若要進行生產環境部署,請參閱我們的 NuGet 套件指南,以確保您選用適合您平台的套件,並查閱 API 參考文件,以獲取所有可用方法與屬性的完整說明。

常見問題

IronQR 支援哪些圖像格式來讀取 QR 碼?

IronQR 支援讀取多種圖像格式的 QR 碼,包括 JPEG、PNG、GIF、TIFF、BMP、WBMP、WebP、ICO、WMF 及 RawFormat。這項全面的格式支援由 IronDrawing 驅動,讓您無需進行格式轉換,即可處理來自各種來源的 QR 碼。

如何在 C# 中從影像檔案讀取 QR 碼?

若要使用 IronQR 讀取 QR 碼,首先需透過 Image.FromFile() 載入圖片,從載入的圖片建立 QrImageInput 物件,接著使用 BarcodeReader.Read() 解碼 QR 碼資料。此方法會傳回結果,您可以透過迭代來存取每個偵測到的 QR 碼資訊。

哪種技術能實現跨不同媒體類型的精準 QR 碼讀取?

IronQR 採用先進的機器學習模型,確保能在不同媒體類型和圖像格式下精準解碼 QR 碼。這種由人工智慧驅動的方法,即使在艱難的圖像條件下,也能維持高準確度。

我可以從單一圖片中讀取多個 QR 碼嗎?

是的,IronQR 能夠從單一圖片中偵測並讀取多個 QR 碼。BarcodeReader.Read 方法會傳回一組結果,讓您能透過 foreach 迴圈遍歷每個偵測到的 QR 碼,以存取個別的 QR 碼資料。

IronQR 所讀取的 QR 碼中可以儲存哪些類型的資料?

IronQR 能解碼儲存於 QR 碼中的各類資料,包括純文字、URL、聯絡資訊及其他形式的結構化資料。解碼後的資訊可透過每個 BarcodeResult 物件的 Value 屬性取得。

Curtis Chau
技術撰稿人

Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

除了開發工作之外,Curtis 對物聯網(IoT)抱有濃厚興趣,致力於探索整合硬體與軟體的創新方法。閒暇時,他喜歡玩遊戲和開發 Discord 機器人,將對科技的熱愛與創意相結合。

準備開始了嗎?
Nuget 下載 67,270 | 版本: 2026.5 just released
Still Scrolling Icon

還在往下捲動嗎?

想要快速確認成果嗎? PM > Install-Package IronQR
執行範例 觀看您的 URL 轉為 QR 碼。