.NET 实现在控制台(Console)输出二维码

本文中如无特别说明 .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("
");
            }
        }

调用:

QRConsole.Output("Hello, World!");
原文地址:https://www.cnblogs.com/stulzq/p/14282461.html