本文中如無特別說明
.NET
指 .NET 5或者更高版本,代碼同樣可用於 .NET Core
無意間看到一個 go 的項目 qrcode ,它在控制台打印了二維碼,便去看了他的實現原理,然后用 C# 實現了一個。
代碼地址:https://github.com/stulzq/QRConsole
效果:
實現
實現原理並不復雜,遍歷二維碼圖片的像素,根據像素的顏色,來設置不同的 Console 顏色,黑色或者白色。
安裝依賴
SixLabors.ImageSharp
ZXing.Net.Bindings.ImageSharp
QRConsole.cs
public static void Output(string text)
{
const int threshold = 180;
//生成二維碼
var writer = new ZXing.ImageSharp.BarcodeWriter<Rgba32>
{
Format = BarcodeFormat.QR_CODE,
Options = new QrCodeEncodingOptions
{
Width = 33,
Height = 33,
Margin = 1
}
};
var image = writer.WriteAsImageSharp<Rgba32>(text);
int[,] points = new int[image.Width, image.Height];
for (var i = 0; i < image.Width; i++)
{
for (var j = 0; j < image.Height; j++)
{
//獲取該像素點的RGB的顏色
var color = image[i,j];
if (color.B<=threshold)
{
points[i, j] = 1;
}
else
{
points[i, j] = 0;
}
}
}
for (var i = 0; i < image.Width; i++)
{
for (var j = 0; j < image.Height; j++)
{
//根據像素點顏色的不同來設置 Console Color
if (points[i, j] == 0)
{
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Black;
Console.Write(" ");
Console.ResetColor();
}
else
{
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.White;
Console.Write(" ");
Console.ResetColor();
}
}
Console.Write("\n");
}
}
調用:
QRConsole.Output("Hello, World!");