在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
條碼掃描器並不總是適用於我們的應用程式。您可能已經擁有條碼的數位影像,並且想知道它在英語文本中所代表的內容。此外,這個掃描器只讀取一維條碼,這些條碼包含有限的數據,且只能在 Windows RT 類庫中使用。二維條碼 (也稱為 QR 碼) 現在已經很常見,並且可以容納更多的信息。
可以創建一個基於 C# 的應用程式來通過簡單的 API 調用和一些編碼步驟來讀取條碼。一個支援 .NET 的應用程式可以在 Windows、macOS 或 Linux 上運行,而不依賴於任何第三方工具或 API。
本文將比較兩個最強大的 .NET Core 應用程式庫用於程式化讀取條碼。這兩個庫是 IronBarcode 和 ZXing.NET。我們將看看 IronBarcode 比 ZXing.NET 更強大和穩健的地方。
Barcode寫rPixelData
類別來自訂條碼格式
屬性QrCodeEncodingOptions
進一步自訂高度、寬度和邊距的類別寫
步驟2中的物件方法ZXing.NET 是一个解码和生成条形码的库 (像 QR Code、PDF 417、EAN、UPC、Aztec、Data Matrix、Codabar)ZXing,全名為 "zebra crossing",是一個基於 Java 的開源庫,支援各種 1D 和 2D 條碼格式。
其主要特點如下:
IronBarcode 是一個 C# 程式庫,允許程式設計師讀取和生成條碼。作為一個領先的條碼程式庫,IronBarcode 支援廣泛的1維和2維條碼,包括裝飾條碼 (彩色和品牌) QR碼。它支援.NET Standard和Core 2及更高版本,允許在Azure、Linux、macOS、Windows和Web上跨平台使用。IronBarcode 是一個著名的.NET系統的類庫或組件,允許C#、VB.NET和F#開發人員使用標準化的編程語言。它能夠使客戶瀏覽掃描標籤並創建新的標準化標籤。它與2D條碼和其他3D標準化條碼配合得非常好。
IronBarcode現在支援2D條碼。它提供了優化這些條碼的顏色、樣式和像素化以及在打印或廣告材料中添加標誌的功能。該庫還能閱讀傾斜和變形的條碼,這是其他條碼軟件可能無法讀取的功能。
在您的ASP.NET Core應用程序中使用NuGet套件管理器主控台安裝以下兩個套件來使用ZXing.NET庫:
Install-Package ZXing.Net
Install-Package ZXing.Net.Bindings.CoreCompat.System.Drawing -Version 0.16.5-beta
或者,使用 NuGet 套件管理器在您的專案中安裝 ZXing.NET。要這樣做,請前往 工具 > NuGet 套件管理器 > 管理解決方案的 NuGet 套件...,然後切換到「瀏覽」標籤並搜尋「ZXing.NET」。
使用 NuGet 包管理器安裝 IronBarcode 或直接從 下載 DLL 產品網站. 該 IronBarcode namespace 包含所有的 IronBarcode 類別。
IronBarcode 可以使用 Visual Studio 的 NuGet 套件管理器安裝:套件名稱是 "Barcode"。
Install-Package BarCode
首先,在專案檔案的根目錄中建立一個名為 'qrr' 的新資料夾。
接下來,我們將創建 QR 文件並將影像系統文件儲存在 'qrr' 資料夾中。
在控制器中,新增 GenerateFile()
方法如下面的原始碼所示。
public ActionResult GenerateFile()
{
return View();
}
[HttpPost]
public ActionResult GenerateFile(string qrText)
{
Byte [] byteArray;
var width = 250; // width of the QR Code
var height = 250; // height of the QR Code
var margin = 0;
var qrCodeWriter = new ZXing.BarcodeWriterPixelData
{
Format = ZXing.BarcodeFormat.QR_CODE,
Options = new QrCodeEncodingOptions
{
Height = height,
Width = width,
Margin = margin
}
};
var pixelData = qrCodeWriter.Write(qrText);
// creating a PNG bitmap from the raw pixel data; if only black and white colors are used it makes no difference if the raw pixel data is BGRA oriented and the bitmap is initialized with RGB
using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb))
{
using (var ms = new MemoryStream())
{
var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
try
{
// we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image
System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan, pixelData.Pixels.Length);
}
finally
{
bitmap.UnlockBits(bitmapData);
}
// save to folder
string fileGuid = Guid.NewGuid().ToString().Substring(0, 4);
bitmap.Save(Server.MapPath("~/qrr") + "/file-" + fileGuid + ".png", System.Drawing.Imaging.ImageFormat.Png);
// save to stream as PNG
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byteArray = ms.ToArray();
}
}
return View(byteArray);
}
public ActionResult GenerateFile()
{
return View();
}
[HttpPost]
public ActionResult GenerateFile(string qrText)
{
Byte [] byteArray;
var width = 250; // width of the QR Code
var height = 250; // height of the QR Code
var margin = 0;
var qrCodeWriter = new ZXing.BarcodeWriterPixelData
{
Format = ZXing.BarcodeFormat.QR_CODE,
Options = new QrCodeEncodingOptions
{
Height = height,
Width = width,
Margin = margin
}
};
var pixelData = qrCodeWriter.Write(qrText);
// creating a PNG bitmap from the raw pixel data; if only black and white colors are used it makes no difference if the raw pixel data is BGRA oriented and the bitmap is initialized with RGB
using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb))
{
using (var ms = new MemoryStream())
{
var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
try
{
// we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image
System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan, pixelData.Pixels.Length);
}
finally
{
bitmap.UnlockBits(bitmapData);
}
// save to folder
string fileGuid = Guid.NewGuid().ToString().Substring(0, 4);
bitmap.Save(Server.MapPath("~/qrr") + "/file-" + fileGuid + ".png", System.Drawing.Imaging.ImageFormat.Png);
// save to stream as PNG
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byteArray = ms.ToArray();
}
}
return View(byteArray);
}
Public Function GenerateFile() As ActionResult
Return View()
End Function
<HttpPost>
Public Function GenerateFile(ByVal qrText As String) As ActionResult
Dim byteArray() As Byte
Dim width = 250 ' width of the QR Code
Dim height = 250 ' height of the QR Code
Dim margin = 0
Dim qrCodeWriter = New ZXing.BarcodeWriterPixelData With {
.Format = ZXing.BarcodeFormat.QR_CODE,
.Options = New QrCodeEncodingOptions With {
.Height = height,
.Width = width,
.Margin = margin
}
}
Dim pixelData = qrCodeWriter.Write(qrText)
' creating a PNG bitmap from the raw pixel data; if only black and white colors are used it makes no difference if the raw pixel data is BGRA oriented and the bitmap is initialized with RGB
Using bitmap = New System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb)
Using ms = New MemoryStream()
Dim bitmapData = bitmap.LockBits(New System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb)
Try
' we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image
System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan, pixelData.Pixels.Length)
Finally
bitmap.UnlockBits(bitmapData)
End Try
' save to folder
Dim fileGuid As String = Guid.NewGuid().ToString().Substring(0, 4)
bitmap.Save(Server.MapPath("~/qrr") & "/file-" & fileGuid & ".png", System.Drawing.Imaging.ImageFormat.Png)
' save to stream as PNG
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
byteArray = ms.ToArray()
End Using
End Using
Return View(byteArray)
End Function
唯一剩下的變更是將 QR 碼檔案保存在 'qrr' 資料夾中。這可以使用下面的兩行代碼來完成。
string fileGuid = Guid.NewGuid().ToString().Substring(0, 4);
bitmap.Save(Server.MapPath("~/qrr") + "/file-" + fileGuid + ".png", System.Drawing.Imaging.ImageFormat.Png);
string fileGuid = Guid.NewGuid().ToString().Substring(0, 4);
bitmap.Save(Server.MapPath("~/qrr") + "/file-" + fileGuid + ".png", System.Drawing.Imaging.ImageFormat.Png);
Dim fileGuid As String = Guid.NewGuid().ToString().Substring(0, 4)
bitmap.Save(Server.MapPath("~/qrr") & "/file-" & fileGuid & ".png", System.Drawing.Imaging.ImageFormat.Png)
您還必須創建 GenerateFile
視圖並在其中包含以下程式碼。GenerateFile
視圖與 Index 視圖相同。
@model Byte []
@using (Html.BeginForm(null, null, FormMethod.Post))
{
<table>
<tbody>
<tr>
<td>
<label>Enter text for creating QR Code</label>
</td>
<td>
// text box to enter text...
<input type="text" name="qrText" />
</td>
</tr>
<tr>
<td colspan="2">
<button>Submit</button>
</td>
</tr>
</tbody>
</table>
}
@{
if (Model != null)
{
<h3>QR Code Successfully Generated</h3>
// img tag to display generated QR code...
<img src="@String.Format("data:image/png;base64,{0}", Convert.ToBase64String(Model))" />
}
}
@model Byte []
@using (Html.BeginForm(null, null, FormMethod.Post))
{
<table>
<tbody>
<tr>
<td>
<label>Enter text for creating QR Code</label>
</td>
<td>
// text box to enter text...
<input type="text" name="qrText" />
</td>
</tr>
<tr>
<td colspan="2">
<button>Submit</button>
</td>
</tr>
</tbody>
</table>
}
@{
if (Model != null)
{
<h3>QR Code Successfully Generated</h3>
// img tag to display generated QR code...
<img src="@String.Format("data:image/png;base64,{0}", Convert.ToBase64String(Model))" />
}
}
model Function [using](Html.BeginForm ByVal As (Nothing, Nothing, FormMethod.Post)) As Byte()
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <table> <tbody> <tr> <td> <label> Enter text for creating QR Code</label> </td> <td> <input type="text" name="qrText" /> </td> </tr> <tr> <td colspan="2"> <button> Submit</button> </td> </tr> </tbody> </table>
"qrText" /> </td> </tr> (Of tr) <td colspan="2"> (Of button) Submit</button> </td> </tr> </tbody> </table>
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <table> <tbody> <tr> <td> <label> Enter text for creating QR Code</label> </td> <td> <input type="text" name="qrText" /> </td> </tr> <tr> <td colspan
"text" name="qrText" /> </td> </tr> (Of tr) <td colspan
(Of table) (Of tbody) (Of tr) (Of td) (Of label) Enter text for creating QR Code</label> </td> (Of td) <input type="text" name
End Function
@
If True Then
If Model IsNot Nothing Then
'INSTANT VB WARNING: Instant VB cannot determine whether both operands of this division are integer types - if they are then you should use the VB integer division operator:
(Of h3) QR Code Successfully Generated</h3> <img src="@String.Format("data:image/png
base64,
If True Then
0
End If
", Convert.ToBase64String(Model))" />
End If
End If
在文字框中輸入任何值並點擊「提交」按鈕。QR Code 將會生成並以 .PNG 檔案存儲在「qrr」資料夾中。
IronBarcode 支援多種常用的條碼格式,包括:
var MyBarCode = IronBarcode.BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode", BarcodeEncoding.Code128);
MyBarCode.SaveAsImage("MyBarCode.png");
MyBarCode.SaveAsGif("MyBarCode.gif");
MyBarCode.SaveAsHtmlFile("MyBarCode.html");
MyBarCode.SaveAsJpeg("MyBarCode.jpg");
MyBarCode.SaveAsPdf("MyBarCode.Pdf");
MyBarCode.SaveAsPng("MyBarCode.png");
MyBarCode.SaveAsTiff("MyBarCode.tiff");
MyBarCode.SaveAsWindowsBitmap("MyBarCode.bmp");
Image MyBarCodeImage = MyBarCode.Image;
Bitmap MyBarCodeBitmap = MyBarCode.ToBitmap();
string DataURL = MyBarCode.ToDataUrl();
string ImgTagForHTML = MyBarCode.ToHtmlTag();
byte [] PngBytes = MyBarCode.ToPngBinaryData();
// Binary barcode image output also works for GIF, JPEG, PDF, PNG, BMP and TIFF
using (System.IO.Stream PdfStream = MyBarCode.ToPdfStream()){
// Stream barcode image output also works for GIF, JPEG, PDF, PNG, BMP and TIFF
}
MyBarCode.StampToExistingPdfPage("ExistingPDF.pdf", 1, 200, 50);
var MyBarCode = IronBarcode.BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode", BarcodeEncoding.Code128);
MyBarCode.SaveAsImage("MyBarCode.png");
MyBarCode.SaveAsGif("MyBarCode.gif");
MyBarCode.SaveAsHtmlFile("MyBarCode.html");
MyBarCode.SaveAsJpeg("MyBarCode.jpg");
MyBarCode.SaveAsPdf("MyBarCode.Pdf");
MyBarCode.SaveAsPng("MyBarCode.png");
MyBarCode.SaveAsTiff("MyBarCode.tiff");
MyBarCode.SaveAsWindowsBitmap("MyBarCode.bmp");
Image MyBarCodeImage = MyBarCode.Image;
Bitmap MyBarCodeBitmap = MyBarCode.ToBitmap();
string DataURL = MyBarCode.ToDataUrl();
string ImgTagForHTML = MyBarCode.ToHtmlTag();
byte [] PngBytes = MyBarCode.ToPngBinaryData();
// Binary barcode image output also works for GIF, JPEG, PDF, PNG, BMP and TIFF
using (System.IO.Stream PdfStream = MyBarCode.ToPdfStream()){
// Stream barcode image output also works for GIF, JPEG, PDF, PNG, BMP and TIFF
}
MyBarCode.StampToExistingPdfPage("ExistingPDF.pdf", 1, 200, 50);
Dim MyBarCode = IronBarcode.BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode", BarcodeEncoding.Code128)
MyBarCode.SaveAsImage("MyBarCode.png")
MyBarCode.SaveAsGif("MyBarCode.gif")
MyBarCode.SaveAsHtmlFile("MyBarCode.html")
MyBarCode.SaveAsJpeg("MyBarCode.jpg")
MyBarCode.SaveAsPdf("MyBarCode.Pdf")
MyBarCode.SaveAsPng("MyBarCode.png")
MyBarCode.SaveAsTiff("MyBarCode.tiff")
MyBarCode.SaveAsWindowsBitmap("MyBarCode.bmp")
Dim MyBarCodeImage As Image = MyBarCode.Image
Dim MyBarCodeBitmap As Bitmap = MyBarCode.ToBitmap()
Dim DataURL As String = MyBarCode.ToDataUrl()
Dim ImgTagForHTML As String = MyBarCode.ToHtmlTag()
Dim PngBytes() As Byte = MyBarCode.ToPngBinaryData()
' Binary barcode image output also works for GIF, JPEG, PDF, PNG, BMP and TIFF
Using PdfStream As System.IO.Stream = MyBarCode.ToPdfStream()
' Stream barcode image output also works for GIF, JPEG, PDF, PNG, BMP and TIFF
End Using
MyBarCode.StampToExistingPdfPage("ExistingPDF.pdf", 1, 200, 50)
另一方面,ZXing 是一個基於 Java 的開源 1D/2D 條碼圖像處理庫。支援 UPC-A、UPC-E、EAN-8、Code 93、Code 128、QR Code、Data Matrix、Aztec、PDF 417 以及其他條碼格式。
要使用 IronBarcode 創建 QR 代碼,我們可以使用 QRCodeWriter
類而不是 BarcodeWriter
類。這個類引入了一些新穎且有趣的功能來創建 QR 代碼。它使我們能夠設置 QR 錯誤更正等級,讓您在 QR 代碼的大小和可讀性之間取得平衡。
// Generate a simple QR Code image and save as PNG
QRCodeWriter.CreateQrCode("hello world", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium).SaveAsPng("MyQR.png");
// Generate a simple QR Code image and save as PNG
QRCodeWriter.CreateQrCode("hello world", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium).SaveAsPng("MyQR.png");
' Generate a simple QR Code image and save as PNG
QRCodeWriter.CreateQrCode("hello world", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium).SaveAsPng("MyQR.png")
錯誤修正使我們能夠指定在現實情況下掃描 QR 碼的難易程度。較高級別的錯誤修正會導致 QR 碼變得更大,具有更多像素和複雜性。在下圖中,我們看到顯示的 QR 碼文件。
我們首先要指定條碼的值和條碼格式,這些格式來自 IronBarcode.BarcodeWriterEncoding
枚舉。接著,我們可以將其保存為圖像、一個 System.Drawing.Image
,或是一個 Bitmap 代碼對象。這就是您所需要的全部源代碼。!
// Generate a simple BarCode image and save as PNG using following namespaces
using IronBarCode;
GeneratedBarcode MyBarCode = IronBarcode.BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode", BarcodeWriterEncoding.Code128);
MyBarCode.SaveAsPng("MyBarCode.png");
// This line opens the image in your default image viewer
System.Diagnostics.Process.Start("MyBarCode.png");
// Generate a simple BarCode image and save as PNG using following namespaces
using IronBarCode;
GeneratedBarcode MyBarCode = IronBarcode.BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode", BarcodeWriterEncoding.Code128);
MyBarCode.SaveAsPng("MyBarCode.png");
// This line opens the image in your default image viewer
System.Diagnostics.Process.Start("MyBarCode.png");
' Generate a simple BarCode image and save as PNG using following namespaces
Imports IronBarCode
Private MyBarCode As GeneratedBarcode = IronBarcode.BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode", BarcodeWriterEncoding.Code128)
MyBarCode.SaveAsPng("MyBarCode.png")
' This line opens the image in your default image viewer
System.Diagnostics.Process.Start("MyBarCode.png")
IronBarcode 也支持對 QR 碼進行樣式設計,例如將商標圖形放置並對齊到圖像正中心的網格。它還可以著色以匹配特定的品牌或圖形識別。
在測試時,請在下面的代碼範例中創建一個商標,看看使用 QRCodeWriter.CreateQRCodeWithLogo
方法有多麼簡單。
// Adding a Logo
var MyQRWithLogo = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/csharp/barcode/", "visual-studio-logo.png", 500);
MyQRWithLogo.ChangeBarCodeColor(System.Drawing.Color.DarkGreen);
// Adding a Logo
var MyQRWithLogo = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/csharp/barcode/", "visual-studio-logo.png", 500);
MyQRWithLogo.ChangeBarCodeColor(System.Drawing.Color.DarkGreen);
' Adding a Logo
Dim MyQRWithLogo = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/csharp/barcode/", "visual-studio-logo.png", 500)
MyQRWithLogo.ChangeBarCodeColor(System.Drawing.Color.DarkGreen)
最後,我們將生成的 QR 碼保存為 PDF 文件。為了方便起見,最後一行代碼將 QR 碼保存為 HTML 文件。
// Adding a Logo
var MyQRWithLogo = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/csharp/barcode/", "visual-studio-logo.png", 500);
MyQRWithLogo.ChangeBarCodeColor(System.Drawing.Color.DarkGreen);
//Save as PDF
MyQRWithLogo.SaveAsPdf("MyQRWithLogo.pdf");
//Also Save as HTML
MyQRWithLogo.SaveAsHtmlFile("MyQRWithLogo.html");
// Adding a Logo
var MyQRWithLogo = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/csharp/barcode/", "visual-studio-logo.png", 500);
MyQRWithLogo.ChangeBarCodeColor(System.Drawing.Color.DarkGreen);
//Save as PDF
MyQRWithLogo.SaveAsPdf("MyQRWithLogo.pdf");
//Also Save as HTML
MyQRWithLogo.SaveAsHtmlFile("MyQRWithLogo.html");
' Adding a Logo
Dim MyQRWithLogo = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/csharp/barcode/", "visual-studio-logo.png", 500)
MyQRWithLogo.ChangeBarCodeColor(System.Drawing.Color.DarkGreen)
'Save as PDF
MyQRWithLogo.SaveAsPdf("MyQRWithLogo.pdf")
'Also Save as HTML
MyQRWithLogo.SaveAsHtmlFile("MyQRWithLogo.html")
如下,我們看看如何只用一行程式碼來創建、設計和導出條形碼。
IronBarcode 包括一個類似於 System.Linq
的流暢 API。 我們創建一個條形碼,設置其邊距,並通過鏈接方法調用將其導出為位圖,只需一行。這非常有用,並使程式碼更易於閱讀。
using IronBarCode;
using System.Drawing;
// Fluent API for Barcode image generation.
string MyValue = "https://ironsoftware.com/csharp/barcode";
Bitmap BarcodeBmp = IronBarcode.BarcodeWriter.CreateBarcode(MyValue, BarcodeEncoding.PDF417).ResizeTo(300,200).SetMargins(100).ToBitmap();
using IronBarCode;
using System.Drawing;
// Fluent API for Barcode image generation.
string MyValue = "https://ironsoftware.com/csharp/barcode";
Bitmap BarcodeBmp = IronBarcode.BarcodeWriter.CreateBarcode(MyValue, BarcodeEncoding.PDF417).ResizeTo(300,200).SetMargins(100).ToBitmap();
Imports IronBarCode
Imports System.Drawing
' Fluent API for Barcode image generation.
Private MyValue As String = "https://ironsoftware.com/csharp/barcode"
Private BarcodeBmp As Bitmap = IronBarcode.BarcodeWriter.CreateBarcode(MyValue, BarcodeEncoding.PDF417).ResizeTo(300,200).SetMargins(100).ToBitmap()
因此,System.Drawing.Image
顯示的 PDF417 條碼如下圖所示:
當您使用 IronBarcode 類別庫與 .NET 條碼閱讀器結合時,讀取條碼或 QR 碼變得輕而易舉。在我們的第一個範例中,我們可以看到只需一行代碼即可讀取條碼。
我們可以獲取條碼的值、圖像、編碼類型和二進制數據 (如果有) 然後將其輸出到控制台。
using IronBarCode;
using System;
BarcodeResult Result = BarcodeReader.QuicklyReadOneBarcode("GetStarted.png");
if (Result !=null && Result.Text == "https://ironsoftware.com/csharp/barcode/")
{
Console.WriteLine("GetStarted was a success. Read Value: " + Result.Text);
}
using IronBarCode;
using System;
BarcodeResult Result = BarcodeReader.QuicklyReadOneBarcode("GetStarted.png");
if (Result !=null && Result.Text == "https://ironsoftware.com/csharp/barcode/")
{
Console.WriteLine("GetStarted was a success. Read Value: " + Result.Text);
}
Imports IronBarCode
Imports System
Private Result As BarcodeResult = BarcodeReader.QuicklyReadOneBarcode("GetStarted.png")
If Result IsNot Nothing AndAlso Result.Text = "https://ironsoftware.com/csharp/barcode/" Then
Console.WriteLine("GetStarted was a success. Read Value: " & Result.Text)
End If
接下来我们将查看如何读取扫描的 PDF 文档,并通过几行代码找到所有的一维条形码。
如您所见,这与从单个文档读取单个条形码非常相似,不同之处在于我们现在知道条形码在哪一页上发现的。
using IronBarCode;
using System;
using System.Drawing;
// Multiple barcodes may be scanned up from a single document or image. A PDF document may also be used as the input image
PagedBarcodeResult [] PDFResults = BarcodeReader.ReadBarcodesFromPdf("MultipleBarcodes.pdf");
// Work with the results
foreach (var PageResult in PDFResults)
{
string Value = PageResult.Value;
int PageNum = PageResult.PageNumber;
System.Drawing.Bitmap Img = PageResult.BarcodeImage;
BarcodeEncoding BarcodeType = PageResult.BarcodeType;
byte [] Binary = PageResult.BinaryValue;
Console.WriteLine(PageResult.Value+" on page "+ PageNum);
}
using IronBarCode;
using System;
using System.Drawing;
// Multiple barcodes may be scanned up from a single document or image. A PDF document may also be used as the input image
PagedBarcodeResult [] PDFResults = BarcodeReader.ReadBarcodesFromPdf("MultipleBarcodes.pdf");
// Work with the results
foreach (var PageResult in PDFResults)
{
string Value = PageResult.Value;
int PageNum = PageResult.PageNumber;
System.Drawing.Bitmap Img = PageResult.BarcodeImage;
BarcodeEncoding BarcodeType = PageResult.BarcodeType;
byte [] Binary = PageResult.BinaryValue;
Console.WriteLine(PageResult.Value+" on page "+ PageNum);
}
Imports IronBarCode
Imports System
Imports System.Drawing
' Multiple barcodes may be scanned up from a single document or image. A PDF document may also be used as the input image
Private PDFResults() As PagedBarcodeResult = BarcodeReader.ReadBarcodesFromPdf("MultipleBarcodes.pdf")
' Work with the results
For Each PageResult In PDFResults
Dim Value As String = PageResult.Value
Dim PageNum As Integer = PageResult.PageNumber
Dim Img As System.Drawing.Bitmap = PageResult.BarcodeImage
Dim BarcodeType As BarcodeEncoding = PageResult.BarcodeType
Dim Binary() As Byte = PageResult.BinaryValue
Console.WriteLine(PageResult.Value &" on page " & PageNum)
Next PageResult
您將獲得包含PDF中所有位圖條碼的結果資料。
// Multi-frame TIFF and GIF images can also be scanned, and multiple threads will be used automatically in the background for improved performance
PagedBarcodeResult [] MultiFrameResults = BarcodeReader.ReadBarcodesFromMultiFrameTiff("Multiframe.tiff", BarcodeEncoding.Code128, BarcodeReader.BarcodeRotationCorrection.High, BarcodeReader.BarcodeImageCorrection.MediumCleanPixels);
foreach (var PageResult in MultiFrameResults)
{
//...
}
// Multi-frame TIFF and GIF images can also be scanned, and multiple threads will be used automatically in the background for improved performance
PagedBarcodeResult [] MultiFrameResults = BarcodeReader.ReadBarcodesFromMultiFrameTiff("Multiframe.tiff", BarcodeEncoding.Code128, BarcodeReader.BarcodeRotationCorrection.High, BarcodeReader.BarcodeImageCorrection.MediumCleanPixels);
foreach (var PageResult in MultiFrameResults)
{
//...
}
' Multi-frame TIFF and GIF images can also be scanned, and multiple threads will be used automatically in the background for improved performance
Dim MultiFrameResults() As PagedBarcodeResult = BarcodeReader.ReadBarcodesFromMultiFrameTiff("Multiframe.tiff", BarcodeEncoding.Code128, BarcodeReader.BarcodeRotationCorrection.High, BarcodeReader.BarcodeImageCorrection.MediumCleanPixels)
For Each PageResult In MultiFrameResults
'...
Next PageResult
以下範例顯示如何從掃描的PDF中讀取QR碼和PDF-417條碼。我們設置了適當的條碼旋轉校正和條碼圖像校正等級,以輕微清理文件,而不會因過度強調需求而造成顯著的性能損失。
// PDF documents can also be scanned, and multiple threads will be used automatically in the background for improved performance
var ScanResults = BarcodeReader.ReadBarcodesFromPdf("Scan.pdf", BarcodeEncoding.All, BarcodeReader.BarcodeRotationCorrection.Low, BarcodeReader.BarcodeImageCorrection.LightlyCleanPixels);
// Work with the results
foreach (var PageResult in ScanResults)
{
string Value = PageResult.Value;
///...
}
// PDF documents can also be scanned, and multiple threads will be used automatically in the background for improved performance
var ScanResults = BarcodeReader.ReadBarcodesFromPdf("Scan.pdf", BarcodeEncoding.All, BarcodeReader.BarcodeRotationCorrection.Low, BarcodeReader.BarcodeImageCorrection.LightlyCleanPixels);
// Work with the results
foreach (var PageResult in ScanResults)
{
string Value = PageResult.Value;
///...
}
' PDF documents can also be scanned, and multiple threads will be used automatically in the background for improved performance
Dim ScanResults = BarcodeReader.ReadBarcodesFromPdf("Scan.pdf", BarcodeEncoding.All, BarcodeReader.BarcodeRotationCorrection.Low, BarcodeReader.BarcodeImageCorrection.LightlyCleanPixels)
' Work with the results
For Each PageResult In ScanResults
Dim Value As String = PageResult.Value
'''...
Next PageResult
以下範例顯示此C#條碼庫甚至可以讀取損壞的條碼縮略圖。
條碼縮略圖尺寸的校正是自動完成的。IronBarcode在C#中使文件可讀。
讀取方法會自動檢測圖像中太小而不可能是合法條碼的部分並將其放大。他們會清理與處理縮略圖相關的所有數位噪音,使其再次可以讀取。
// Small or 'Thumbnail' barcode images are automatically detected by IronBarcode and corrected wherever possible even if they have much digital noise.
BarcodeResult SmallResult = BarcodeReader.QuicklyReadOneBarcode("ThumbnailOfBarcode.gif", BarcodeEncoding.Code128);
// Small or 'Thumbnail' barcode images are automatically detected by IronBarcode and corrected wherever possible even if they have much digital noise.
BarcodeResult SmallResult = BarcodeReader.QuicklyReadOneBarcode("ThumbnailOfBarcode.gif", BarcodeEncoding.Code128);
' Small or 'Thumbnail' barcode images are automatically detected by IronBarcode and corrected wherever possible even if they have much digital noise.
Dim SmallResult As BarcodeResult = BarcodeReader.QuicklyReadOneBarcode("ThumbnailOfBarcode.gif", BarcodeEncoding.Code128)
在現實場景中,我們可能需要從不完美的圖像中讀取條碼。它們可能是傾斜的圖像或帶有數位噪點的照片。這對於大多數開源 .NET 條碼生成和讀取庫來說是不可能的。IronBarcode,則使從不完美的圖像中讀取條碼變得輕而易舉。
我們現在來看看 ReadASingleBarcode
方法。借助其 RotationCorrection
參數,IronBarcode 會嘗試對數位樣本進行去傾斜並讀取條碼。
using IronBarCode;
using System;
using System.Drawing;
// All BarcodeResult.Read methods provide the developer with control to correct image and photograph correction and straightening rotation and perspective from skewed images
// * RotationCorrection e.g BarcodeReader.BarcodeRotationCorrection.Extreme un-rotates and removes perspective from barcode images.
// * ImageCorrection e.g BarcodeReader.BarcodeImageCorrection.DeepCleanPixels separates barcodes from background imagery and digital noise.
// * BarcodeEncoding e.g. BarcodeEncoding.Code128, Setting a specific Barcode format improves speed and reduces the risk of false positive results
// Example with a photo image
var PhotoResult = BarcodeReader.ReadASingleBarcode("Photo.png", BarcodeEncoding.Code128, BarcodeReader.BarcodeRotationCorrection.Medium, BarcodeReader.BarcodeImageCorrection.DeepCleanPixels);
string Value = PhotoResult.Value;
System.Drawing.Bitmap Img = PhotoResult.BarcodeImage;
BarcodeEncoding BarcodeType = PhotoResult.BarcodeType;
byte [] Binary = PhotoResult.BinaryValue;
Console.WriteLine(PhotoResult.Value);
using IronBarCode;
using System;
using System.Drawing;
// All BarcodeResult.Read methods provide the developer with control to correct image and photograph correction and straightening rotation and perspective from skewed images
// * RotationCorrection e.g BarcodeReader.BarcodeRotationCorrection.Extreme un-rotates and removes perspective from barcode images.
// * ImageCorrection e.g BarcodeReader.BarcodeImageCorrection.DeepCleanPixels separates barcodes from background imagery and digital noise.
// * BarcodeEncoding e.g. BarcodeEncoding.Code128, Setting a specific Barcode format improves speed and reduces the risk of false positive results
// Example with a photo image
var PhotoResult = BarcodeReader.ReadASingleBarcode("Photo.png", BarcodeEncoding.Code128, BarcodeReader.BarcodeRotationCorrection.Medium, BarcodeReader.BarcodeImageCorrection.DeepCleanPixels);
string Value = PhotoResult.Value;
System.Drawing.Bitmap Img = PhotoResult.BarcodeImage;
BarcodeEncoding BarcodeType = PhotoResult.BarcodeType;
byte [] Binary = PhotoResult.BinaryValue;
Console.WriteLine(PhotoResult.Value);
Imports IronBarCode
Imports System
Imports System.Drawing
' All BarcodeResult.Read methods provide the developer with control to correct image and photograph correction and straightening rotation and perspective from skewed images
' * RotationCorrection e.g BarcodeReader.BarcodeRotationCorrection.Extreme un-rotates and removes perspective from barcode images.
' * ImageCorrection e.g BarcodeReader.BarcodeImageCorrection.DeepCleanPixels separates barcodes from background imagery and digital noise.
' * BarcodeEncoding e.g. BarcodeEncoding.Code128, Setting a specific Barcode format improves speed and reduces the risk of false positive results
' Example with a photo image
Private PhotoResult = BarcodeReader.ReadASingleBarcode("Photo.png", BarcodeEncoding.Code128, BarcodeReader.BarcodeRotationCorrection.Medium, BarcodeReader.BarcodeImageCorrection.DeepCleanPixels)
Private Value As String = PhotoResult.Value
Private Img As System.Drawing.Bitmap = PhotoResult.BarcodeImage
Private BarcodeType As BarcodeEncoding = PhotoResult.BarcodeType
Private Binary() As Byte = PhotoResult.BinaryValue
Console.WriteLine(PhotoResult.Value)
IronBarcode 也能同時讀取多個條碼。我們在創建文件列表並使用條碼讀取器讀取大量文件時,IronBarcode 可以獲得更好的結果。ReadBarcodesMultithreaded
方法在條碼掃描過程中使用多個執行緒和潛在的所有 CPU 核心,比逐一讀取條碼的速度快很多倍。
// The BarcodeResult.ReadBarcodesMultiThreaded method allows for faster barcode scanning of multiple images or PDFs. All threads are automatically managed by IronBarcode.
var ListOfDocuments = new [] { "Image1.png", "image2.JPG", "image3.pdf" };
PagedBarcodeResult [] BatchResults = BarcodeReader.ReadBarcodesMultiThreaded(ListOfDocuments);
// Work with the results
foreach (var Result in BatchResults)
{
string Value = Result.Value;
//...
}
// The BarcodeResult.ReadBarcodesMultiThreaded method allows for faster barcode scanning of multiple images or PDFs. All threads are automatically managed by IronBarcode.
var ListOfDocuments = new [] { "Image1.png", "image2.JPG", "image3.pdf" };
PagedBarcodeResult [] BatchResults = BarcodeReader.ReadBarcodesMultiThreaded(ListOfDocuments);
// Work with the results
foreach (var Result in BatchResults)
{
string Value = Result.Value;
//...
}
' The BarcodeResult.ReadBarcodesMultiThreaded method allows for faster barcode scanning of multiple images or PDFs. All threads are automatically managed by IronBarcode.
Dim ListOfDocuments = { "Image1.png", "image2.JPG", "image3.pdf" }
Dim BatchResults() As PagedBarcodeResult = BarcodeReader.ReadBarcodesMultiThreaded(ListOfDocuments)
' Work with the results
For Each Result In BatchResults
Dim Value As String = Result.Value
'...
Next Result
要讀取 QR 碼文件,請在控制器中添加 ViewFile
操作方法,如下所示。
public ActionResult ViewFile()
{
List<KeyValuePair<string, string>> fileData = new List<KeyValuePair<string, string>>();
KeyValuePair<string, string> data;
string [] files = Directory.GetFiles(Server.MapPath("~/qrr"));
foreach (string file in files)
{
// create a barcode reader instance
IBarcodeReader reader = new BarcodeReader();
// load a bitmap
var barcodeBitmap = (Bitmap)Image.FromFile(Server.MapPath("~/qrr") + "/" + Path.GetFileName(file));
// detect and decode the barcode inside the bitmap
var result = reader.Decode(barcodeBitmap);
// do something with the result
data = new KeyValuePair<string, string>(result.ToString(), "/QR/" + Path.GetFileName(file));
fileData.Add(data);
}
return View(fileData);
}
public ActionResult ViewFile()
{
List<KeyValuePair<string, string>> fileData = new List<KeyValuePair<string, string>>();
KeyValuePair<string, string> data;
string [] files = Directory.GetFiles(Server.MapPath("~/qrr"));
foreach (string file in files)
{
// create a barcode reader instance
IBarcodeReader reader = new BarcodeReader();
// load a bitmap
var barcodeBitmap = (Bitmap)Image.FromFile(Server.MapPath("~/qrr") + "/" + Path.GetFileName(file));
// detect and decode the barcode inside the bitmap
var result = reader.Decode(barcodeBitmap);
// do something with the result
data = new KeyValuePair<string, string>(result.ToString(), "/QR/" + Path.GetFileName(file));
fileData.Add(data);
}
return View(fileData);
}
Public Function ViewFile() As ActionResult
Dim fileData As New List(Of KeyValuePair(Of String, String))()
Dim data As KeyValuePair(Of String, String)
Dim files() As String = Directory.GetFiles(Server.MapPath("~/qrr"))
For Each file As String In files
' create a barcode reader instance
Dim reader As IBarcodeReader = New BarcodeReader()
' load a bitmap
Dim barcodeBitmap = CType(Image.FromFile(Server.MapPath("~/qrr") & "/" & Path.GetFileName(file)), Bitmap)
' detect and decode the barcode inside the bitmap
Dim result = reader.Decode(barcodeBitmap)
' do something with the result
data = New KeyValuePair(Of String, String)(result.ToString(), "/QR/" & Path.GetFileName(file))
fileData.Add(data)
Next file
Return View(fileData)
End Function
// create a barcode reader instance
BarcodeReader reader = new BarcodeReader();
// load a bitmap
var barcodeBitmap = (Bitmap)Image.LoadFrom("C:\\sample-barcode-image.png");
// detect and decode the barcode inside the bitmap
var result = reader.Decode(barcodeBitmap);
// do something with the result
if (result != null)
{
txtDecoderType.Text = result.BarcodeFormat.ToString();
txtDecoderContent.Text = result.Text;
}
// create a barcode reader instance
BarcodeReader reader = new BarcodeReader();
// load a bitmap
var barcodeBitmap = (Bitmap)Image.LoadFrom("C:\\sample-barcode-image.png");
// detect and decode the barcode inside the bitmap
var result = reader.Decode(barcodeBitmap);
// do something with the result
if (result != null)
{
txtDecoderType.Text = result.BarcodeFormat.ToString();
txtDecoderContent.Text = result.Text;
}
' create a barcode reader instance
Dim reader As New BarcodeReader()
' load a bitmap
Dim barcodeBitmap = CType(Image.LoadFrom("C:\sample-barcode-image.png"), Bitmap)
' detect and decode the barcode inside the bitmap
Dim result = reader.Decode(barcodeBitmap)
' do something with the result
If result IsNot Nothing Then
txtDecoderType.Text = result.BarcodeFormat.ToString()
txtDecoderContent.Text = result.Text
End If
ZXing Decoder Online 是一個在線條碼和QR碼掃描器,支持解碼。上傳PNG或其他格式的QR碼圖像,它會開始解碼。同樣,您也可以為任何數據生成QR碼。大多數情況下,那些信息是您希望編碼到QR碼中的URL或文本。
導航至ZXing Decoder網站。
ZXing.NET 庫是一個免費的開源庫,它允許您構建條碼閱讀應用程式,但它基於 Apache 許可證,這不允許它自由用於商業目的。
IronBarcode 的開發者許可證是免費提供的。IronBarcode 有一個獨特的定價方案:Lite 套餐從 $749 開始,沒有額外成本。SaaS 和 OEM 物品也可以再次分發。每個許可證包括永續許可證、開發/測試/生產有效性、30 天退款保證,以及一年的軟體支援和升級。 (一次性購買). 訪問這個 頁面 查看IronBarcode的完整定價和許可資訊。
IronBarcode 包含一個易於使用的 API,供開發人員在 .NET 中讀寫條碼,使其在實際應用情況下優化了準確性和低誤差率。
例如,BarcodeWriter
類別會驗證並糾正 UPCA 和 UPCE 條碼上的「校驗和」。它也會對長度不足以進入特定位數格式的數字進行「零填充」。如果您的數據與指定的數據格式不兼容,IronBarcode 將通知開發人員可以使用的更合適的條碼格式。
IronBarcode 在讀取條碼方面表現出色,即使條碼是從掃描或從照片圖像中讀取的,換句話說,當圖像在圖形上不完美且不是機器生成的截圖時。
IronBarcode 是基於 ZXing.NET 構建的 (斑馬線) 核心,具備更強的處理能力。IronBarcode 提供了一個易於使用的 API,並且與 ZXing.NET 核心庫相比,錯誤率較低。不僅如此,IronBarcode 還支援比通常的 ZXing.NET 庫更廣泛的條碼格式。
IronBarcode 是 ZXing.NET 的改良版本,為用戶提供商業用途的平台,並且可以在多個平台上使用同一個包。它還提供完整的技術支援,隨時準備在需要時幫助您。
IronBarcode 包括自動旋轉、透視校正和數位噪聲校正,並且可以檢測圖像中條碼的類型。
總而言之,IronBarcode 是一個多功能的 .NET 軟體庫和 C# QR 碼生成器,用於讀取各種條碼格式,包括截圖、照片、掃描或其他不完美的現實世界圖像。
IronBarcode 是創建和識別條碼最有效的庫之一。在創建和識別條碼方面,它也是最快的庫之一。該庫與不同的操作系統兼容。它易於設計並支持多種條碼格式。此外,還支持各種符號、格式和字符。
ZXing.NET 條碼是一個強大的庫,能夠生成和識別各種圖像格式的條碼。我們可以讀取和創建多種格式的圖像。ZXing.NET 還允許您更改條碼的外觀,如更改其高度、寬度、條碼文本等。
與 ZXing.NET 相比,IronBarcode 提供可靠的許可和支持。IronBarcode 的費用為 $749。儘管 ZXing 是免費的,但它不允許商業使用,也缺乏全面的支持。除了比 ZXing.NET 更靈活之外,IronBarcode 解決方案還具有更多的功能。因此,可以看出 IronBarcode 相較於 ZXing.NET 具有很大的優勢。
在比較識別和生成條碼的處理時間時,IronBarcode 比 ZXing.NET 更具優勢。IronBarcode 還具有多個屬性,允許我們從不同的圖像格式和 PDF 文件中讀取條碼。它還允許我們在條碼或 QR 碼中包含圖像,這在其他任何庫中都是不可用的。
IronBarcode 在開發初期是免費的。你可以獲得一份 免費試用 用於生產級或商業用途。根據開發者的需求,IronBarcode 提供三種定價級別。您可以選擇最能滿足您需求的解決方案。您現在可以以購買兩個 Iron Software 產品的價格,獲得五個 Iron Software 產品套裝。請訪問此 網站 如需更多資訊。