ZXing.NET 是一個開源的、功能強大的二維碼處理庫,它能夠對二維碼進行解碼(讀取信息)和編碼(生成二維碼)。ZXing 是 "Zebra Crossing" 的縮寫,是一個跨平臺的、用於解碼和生成條形碼和二維碼的庫。以下是一些 ZXing.Net 的主要功能通過實例講解。 1. 生成二維碼 u ...
ZXing.NET 是一個開源的、功能強大的二維碼處理庫,它能夠對二維碼進行解碼(讀取信息)和編碼(生成二維碼)。ZXing 是 "Zebra Crossing" 的縮寫,是一個跨平臺的、用於解碼和生成條形碼和二維碼的庫。以下是一些 ZXing.Net 的主要功能通過實例講解。
1. 生成二維碼
using System;
using System.Drawing;
using ZXing;
using ZXing.QrCode;
class Program
{
static void Main()
{
// 創建 QR Code 編碼器實例
var writer = new BarcodeWriter();
writer.Format = BarcodeFormat.QR_CODE;
// 設置二維碼內容
string content = "Hello, ZXing.Net!";
// 生成二維碼圖片
Bitmap qrCodeBitmap = writer.Write(content);
// 保存生成的二維碼圖片(這裡假設保存路徑為 "qrcode.png")
qrCodeBitmap.Save("qrcode.png");
Console.WriteLine("已生成二維碼.");
}
}
2. 解碼二維碼
using System;
using System.Drawing;
using ZXing;
class Program
{
static void Main()
{
// 創建二維碼解碼器實例
var reader = new BarcodeReader();
// 讀取二維碼圖片(這裡假設圖片路徑為 "qrcode.png")
Bitmap qrCodeBitmap = (Bitmap)Bitmap.FromFile("qrcode.png");
// 解碼二維碼
var result = reader.Decode(qrCodeBitmap);
// 輸出解碼結果
if (result != null)
{
Console.WriteLine($"解碼結果: {result.Text}");
}
else
{
Console.WriteLine("無法解碼二維碼.");
}
}
}
3. 自定義二維碼樣式
using System;
using System.Drawing;
using ZXing;
using ZXing.QrCode;
using ZXing.Rendering;
class Program
{
static void Main()
{
// 創建 QR Code 編碼器實例
var writer = new BarcodeWriter();
writer.Format = BarcodeFormat.QR_CODE;
// 設置二維碼內容
string content = "Custom Style";
// 設置自定義樣式
var renderer = new BitmapRenderer();
renderer.Background = Color.Yellow;
renderer.Foreground = Color.DarkBlue;
writer.Renderer = renderer;
// 生成二維碼圖片
Bitmap qrCodeBitmap = writer.Write(content);
// 保存生成的二維碼圖片(這裡假設保存路徑為 "custom_style_qrcode.png")
qrCodeBitmap.Save("custom_style_qrcode.png");
Console.WriteLine("已生成帶有自定義樣式的二維碼.");
}
}
4. 解碼帶有Logo的二維碼
using System;
using System.Drawing;
using ZXing;
using ZXing.Common;
class Program
{
static void Main()
{
// 創建二維碼解碼器實例
var reader = new BarcodeReader();
// 讀取帶有Logo的二維碼圖片(這裡假設圖片路徑為 "qrcode_with_logo.png")
Bitmap qrCodeBitmap = (Bitmap)Bitmap.FromFile("qrcode_with_logo.png");
// 解碼二維碼
var result = reader.Decode(qrCodeBitmap);
// 輸出解碼結果
if (result != null)
{
Console.WriteLine($"解碼結果: {result.Text}");
}
else
{
Console.WriteLine("無法解碼二維碼.");
}
}
}
這些示例演示了 ZXing.Net 的一些基本功能,包括生成和解碼普通二維碼、自定義樣式的二維碼以及解碼帶有Logo的二維碼。你可以根據實際需求進一步定製和擴展這些功能。請確保將 ZXing.Net NuGet 包添加到你的項目中。