如何使用C#在ASP.NET Core中轻松实现QRCoder

by Yogi

由瑜伽士

如何使用C#在ASP.NET Core中轻松实现QRCoder (How to easily implement QRCoder in ASP.NET Core using C#)

QRCoder is a very popular QR Code implementation library written in C#. It is available in GitHub. Here I am going to implement the QRCoder library to generate QR Codes in my ASP.NET Core application. I will also be using C#.

QRCoder是使用C#编写的非常流行的QR Code实现库。 它在GitHub可用 在这里,我将实现QRCoder库以在我的ASP.NET Core应用程序中生成QR代码。 我还将使用C#。

I will implement QRCoder in 3 ways, which are:

我将以3种方式实现QRCoder:

1. Create QR Code Bitmap image for any text.

1.为任何文本创建QR码位图图像。

2. Create QR Code File (.qrr) for any text and then save these files in the application.

2.为任何文本创建QR码文件(.qrr),然后将这些文件保存在应用程序中。

3. Read and display all the QR Code Files (.qrr).

3.阅读并显示所有QR码文件(.qrr)。

Let’s start with the Installation of QRCoder in ASP.NET Core Framework.

让我们开始在ASP.NET Core Framework中安装QRCoder。

You can download the full code from my GitHub Respositiory.

您可以从我的GitHub Repositiory下载完整的代码

安装 (Installation)

Install QRCoder via NuGet Package Manager. If you want to use NuGet, just search for “QRCoder” or run the following command in the NuGet Package Manager console:

通过NuGet软件包管理器安装QRCoder。 如果要使用NuGet,只需搜索“ QRCoder”或在NuGet软件包管理器控制台中运行以下命令:

PM> Install-Package QRCoder

PM> Install-Package QRCoder

The QRCoder will install in 1 minute and will be ready to use.

QRCoder将在1分钟内安装好并可以使用。

Now let us start with the implementation of QRCoder in the 3 ways mentioned above.

现在让我们从上述3种方式开始QRCoder的实现。

为任何文本创建QR码位图图像 (Create QR Code Bitmap image for any text)

Create a new Controller called ‘QRCoderController’ inside the Controllers folder. The controller will be created and it will have just one Action Method called ‘Index’ in it:

在Controllers文件夹中创建一个名为“ QRCoderController ”的新Controller。 控制器将被创建,并且其中只有一个名为“ Index ”的操作方法:

public IActionResult Index()
{
    return View();
}

Import the following namespaces in the controller:

在控制器中导入以下名称空间:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using QRCoder;

Next, add the Index Action of type [HttpPost] to the controller:

接下来,将类型为[HttpPost]的Index Action添加到控制器:

[HttpPost]
public IActionResult Index(string qrText)
{
    QRCodeGenerator qrGenerator = new QRCodeGenerator();
    QRCodeData qrCodeData = qrGenerator.CreateQrCode(qrText,
    QRCodeGenerator.ECCLevel.Q);
    QRCode qrCode = new QRCode(qrCodeData);
    Bitmap qrCodeImage = qrCode.GetGraphic(20);
    return View(BitmapToBytes(qrCodeImage));
}
This Index Action receives a string parameter called ‘qrText’. It contains the text that is provided by an Input control defined in the View. This text will be converted to QR Code Bitmap image. The following code lines do this work:
该索引操作接收一个名为“ qrText”的字符串参数。 它包含由视图中定义的输入控件提供的文本。 此文本将转换为QR码位图图像。 以下代码行可以完成这项工作:
QRCodeGenerator qrGenerator = new QRCodeGenerator();

QRCodeData qrCodeData = qrGenerator.CreateQrCode(qrText, QRCodeGenerator.ECCLevel.Q);

QRCode qrCode = new QRCode(qrCodeData);
Bitmap qrCodeImage = qrCode.GetGraphic(20);

The QRCode object (‘qrCode’) defined calls a static function called ‘BitmapToBytes()’. The role of this function is to convert the Bitmap image to ‘Byte[]’.

定义的QRCode对象(“ qrCode ”)调用一个名为“ BitmapToBytes() ”的静态函数。 该功能的作用是将位图图像转换为“ Byte[] ”。

Add this function to your controller:

将此功能添加到您的控制器:

private static Byte[] BitmapToBytes(Bitmap img)
{
    using (MemoryStream stream = new MemoryStream())
    {
        img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
        return stream.ToArray();
    }
}

Finally create the Index View inside the ‘Views/QRCoder’ folder with the following code:

最后,使用以下代码在“ Views/QRCoder ”文件夹内创建索引视图:

@model Byte[]
@{
    Layout = null;
}

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width" />
  <title>Implementing QRCoder in ASP.NET Core - Create QR Code</title>
  <style>
    body {
      background: #111 no-repeat;
      background-image: -webkit-gradient(radial, 50% 0, 150, 50% 0, 300, from(#444), to(#111));
    }

    h1,
    h2,
    h3 {
      text-align: center;
      color: #FFF;
      margin: 5px 0;
    }

    h1 {
      font-size: 30px;
    }

    h2 a {
      font-size: 25px;
      color: #0184e3;
      text-decoration: none;
    }

    h3 {
      font-size: 23px;
      border-bottom: solid 3px #CCC;
      padding-bottom: 10px;
    }

    h3 a {
      color: #00e8ff;
      text-decoration: none;
    }

    h3 a:hover,
    h2 a:hover {
      text-decoration: underline;
    }

    .container {
      width: 800px;
      margin: auto;
      color: #FFF;
      font-size: 25px;
    }

    .container #content {
      border: dashed 2px #CCC;
      padding: 10px;
    }

    #reset {
      padding: 5px 10px;
      background: #4CAF50;
      border: none;
      color: #FFF;
      cursor: pointer;
    }

    #reset:hover {
      color: #4CAF50;
      background: #FFF;
    }

    #viewContent table {
      width: 100%;
    }

    #viewContent table tr {
      height: 80px;
      background: darkcyan;
    }

    #viewContent table tr td {
      width: 50%;
      padding-left: 5px;
    }
  </style>
</head>

<body>
  <div class="container">
    <div id="content">
      <h1>Implementing QRCoder in ASP.NET Core - Create QR Code</h1>
      <h2>
        <a href="http://www.yogihosting.com/category/aspnet-core/">Read the tutorial on YogiHosting » </a>
        <button id="reset" onclick="location=''">Reset »</button>
      </h2>
      <div id="viewContent">
        @using (Html.BeginForm(null, null, FormMethod.Post)) {
        <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>
        }
      </div>
      
      @{
        if (Model != null)
        {
          <h3>QR Code Successfully Generated</h3>
          <img src="@String.Format("data:image/png;base64,{0}", Convert.ToBase64String(Model))" />
        }
      }
    </div>
  </div>
</body>
</html>

The Index View has an ‘input’ control. The user enters their text into this control to create the QR Code:

索引视图具有“ input ”控件。 用户将其文本输入此控件以创建QR码:

<input type="text" name="qrText" />

<input type="text" name="qrText" />

Once the QR Code is generated by the Index Action method, its ‘byte’ array is returned to the View as model and then the bitmap image is displayed by the below code:

通过Index Action方法生成QR代码后,其“ byte ”数组将作为模型返回到View,然后通过以下代码显示位图图像:

@{
  if (Model != null)
  {
    <h3>QR Code Successfully Generated</h3>
    <img src="@String.Format("data:image/png;base64,{0}", Convert.ToBase64String(Model))" />
  }
}
测试代码 (Testing the Code)

Run your application and go to the URL — ‘http://localhost:50755/QRCoder’ to invoke the Index Action method.

运行您的应用程序并转到URL http://localhost:50755/QRCoder '以调用Index Action方法。

In the text box, add your text and click the submit button to create the QR Code Bitmap image.

在文本框中,添加文本,然后单击提交按钮以创建QR码位图图像。

See this image which illustrates it working:

请参阅此图片,说明其工作原理:

为任何文本创建QR码文件(.qrr),然后将这些文件保存在应用程序中 (Create QR Code File (.qrr) for any text and then save these files in the application)

You can also generate QR Code files for a text and save it in your website. These files have .qrr extension.

您还可以为文本生成QR Code文件,并将其保存在您的网站中。 这些文件有。 qrr扩展名。

To your controller add the following Action methods called ‘GenerateFile’:

向您的控制器添加以下名为“ GenerateFile ”的Action方法:

public IActionResult GenerateFile()
{
  return View();
}

[HttpPost]
public IActionResult GenerateFile(string qrText)
{
  QRCodeGenerator qrGenerator = new QRCodeGenerator();
  QRCodeData qrCodeData = qrGenerator.CreateQrCode(qrText,   QRCodeGenerator.ECCLevel.Q);
  
  string fileGuid = Guid.NewGuid().ToString().Substring(0, 4);
  
  qrCodeData.SaveRawData("wwwroot/qrr/file-" + fileGuid + ".qrr", QRCodeData.Compression.Uncompressed);
  
  QRCodeData qrCodeData1 = new QRCodeData("wwwroot/qrr/file-" + fileGuid + ".qrr", QRCodeData.Compression.Uncompressed);
  
  QRCode qrCode = new QRCode(qrCodeData1);
  Bitmap qrCodeImage = qrCode.GetGraphic(20);
  return View(BitmapToBytes(qrCodeImage));
}

The [HttpPost] version of this action method generates the QR Code files inside the ‘wwwroot/qrr’ folder. The code that does this work is the following:

此操作方法的[HttpPost]版本在' wwwroot/qrr '文件夹内生成QR Code文件。 可以完成此工作的代码如下:

QRCodeGenerator qrGenerator = new QRCodeGenerator();

QRCodeData qrCodeData = qrGenerator.CreateQrCode(qrText, QRCodeGenerator.ECCLevel.Q);

string fileGuid = Guid.NewGuid().ToString().Substring(0, 4);

qrCodeData.SaveRawData("wwwroot/qrr/file-" + fileGuid + ".qrr", QRCodeData.Compression.Uncompressed);

Once the .qrr file is created then I am simply reading it for its saved location in the website. Then I am converting it to Bitmap type and finally sending the image’s bytes to the view. The corresponding code is:

创建.qrr文件后,我只是在阅读该文件以了解其在网站中的保存位置。 然后,我将其转换为Bitmap类型,最后将图像的字节发送到视图。 相应的代码是:

QRCodeData qrCodeData1 = new QRCodeData("wwwroot/qrr/file-" + fileGuid + ".qrr", QRCodeData.Compression.Uncompressed);

QRCode qrCode = new QRCode(qrCodeData1);
Bitmap qrCodeImage = qrCode.GetGraphic(20);

return View(BitmapToBytes(qrCodeImage));

Next, add the GenerateFile view inside the ‘Views/QRCoder’ folder and add the following code to it:

接下来,在“ Views/QRCoder ”文件夹内添加GenerateFile视图,并向其中添加以下代码:

@model Byte[]
@{
    Layout = null;
}

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width" />
  <title>Implementing QRCoder in ASP.NET Core - Create QR Code File</title>
  <style>
    body {
      background: #111 no-repeat;
      background-image: -webkit-gradient(radial, 50% 0, 150, 50% 0, 300, from(#444), to(#111));
    }

    h1,
    h2,
    h3 {
      text-align: center;
      color: #FFF;
      margin: 5px 0;
    }

    h1 {
      font-size: 30px;
    }

    h2 a {
      font-size: 25px;
      color: #0184e3;
      text-decoration: none;
    }

    h3 {
      font-size: 23px;
      border-bottom: solid 3px #CCC;
      padding-bottom: 10px;
    }

    h3 a {
      color: #00e8ff;
      text-decoration: none;
    }

    h3 a:hover,
    h2 a:hover {
      text-decoration: underline;
    }

    .container {
      width: 800px;
      margin: auto;
      color: #FFF;
      font-size: 25px;
    }

    .container #content {
      border: dashed 2px #CCC;
      padding: 10px;
    }

    #reset {
      padding: 5px 10px;
      background: #4CAF50;
      border: none;
      color: #FFF;
      cursor: pointer;
    }

    #reset:hover {
      color: #4CAF50;
      background: #FFF;
    }

    #viewContent table {
      width: 100%;
    }

    #viewContent table tr {
      height: 80px;
      background: darkcyan;
    }

    #viewContent table tr td {
      width: 50%;
      padding-left: 5px;
    }
  </style>
</head>

<body>
  <div class="container">
    <div id="content">
      <h1>Implementing QRCoder in ASP.NET Core - Create QR Code File</h1>
      <h2>
        <a href="http://www.yogihosting.com/category/aspnet-core/">Read the tutorial on YogiHosting » </a>
        <button id="reset" onclick="location=''">Reset »</button>
      </h2>
      <div id="viewContent">
        @using (Html.BeginForm(null, null, FormMethod.Post)) {
        <table>
          <tbody>
            <tr>
              <td>
                <label>Enter text for creating QR File</label>
              </td>
              <td>
                <input type="text" name="qrText" />
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <button>Submit</button>
              </td>
            </tr>
          </tbody>
        </table>
        }
      </div>
      @{ if (Model != null) {
      <h3>QR Code file Successfully Generated</h3>
      <img src="@String.Format(" data:image/png;base64,{0} ", Convert.ToBase64String(Model))" /> } }
    </div>
  </div>
</body>

</html>

The code of this View is exactly similar to the ‘Index’ View and works exactly like it.

该视图的代码与“索引”视图完全相似,并且工作原理完全相同。

The URL to invoke this View is ‘http://localhost:50755/QRCoder/GenerateFile’.

调用该视图的URL是' http://localhost:50755/QRCoder/GenerateFile '。

读取并显示所有QR码文件(.qrr) (Read and display all the QR Code Files (.qrr))

You can also read all the .qrr files saved in the website. Go to your controller and add a new action called ‘ViewFile’:

您还可以阅读网站中保存的所有.qrr文件。 转到您的控制器并添加一个名为“ ViewFile”的新操作:

public IActionResult ViewFile()
{
  List<KeyValuePair<string, Byte[]>> fileData=new List<KeyValuePair<string, byte[]>>();
  
  KeyValuePair<string, Byte[]> data;
  string[] files = Directory.GetFiles("wwwroot/qrr");
  foreach (string file in files)
  {
    QRCodeData qrCodeData = new QRCodeData(file, QRCodeData.Compression.Uncompressed);
    
    QRCode qrCode = new QRCode(qrCodeData);
    Bitmap qrCodeImage = qrCode.GetGraphic(20);
    
    Byte[] byteData = BitmapToBytes(qrCodeImage);
    data = new KeyValuePair<string, Byte[]>(Path.GetFileName(file), byteData);
    fileData.Add(data);
  }
  return View(fileData);
}

In this action method, I read the filed located in the ‘qrr’ folder using the code:

在此操作方法中,我使用以下代码读取了位于“ qrr”文件夹中的文件:

Directory.GetFiles("wwwroot/qrr")

Then I add each qrr file’s bytes and name inside a List<KeyValuePair<string, Byte[]>> object.

然后,我在List<KeyValuePair<string, Byte[]>>对象中添加每个qrr文件的字节和名称。

This object is returned to the View at the end:

该对象最后返回到视图:

return View(fileData);

Finally create the ‘ViewFile’ View inside the ‘Views/QRCoder’ folder with the following code:

最后,使用以下代码在“ Views/QRCoder ”文件夹中创建“ ViewFile ”视图:

@model List
<KeyValuePair<string, Byte[]>>
@{
    Layout = null;
}

  <!DOCTYPE html>
  <html>

  <head>
    <meta name="viewport" content="width=device-width" />
    <title>Implementing QRCoder in ASP.NET Core - View QR Code Files</title>
    <style>
      body {
        background: #111 no-repeat;
        background-image: -webkit-gradient(radial, 50% 0, 150, 50% 0, 300, from(#444), to(#111));
      }

      h1,
      h2,
      h3 {
        text-align: center;
        color: #FFF;
        margin: 5px 0;
      }

      h1 {
        font-size: 30px;
      }

      h2 a {
        font-size: 25px;
        color: #0184e3;
        text-decoration: none;
      }

      h3 {
        font-size: 23px;
        border-bottom: solid 3px #CCC;
        padding-bottom: 10px;
      }

      h3 a {
        color: #00e8ff;
        text-decoration: none;
      }

      h3 a:hover,
      h2 a:hover {
        text-decoration: underline;
      }

      .container {
        width: 800px;
        margin: auto;
        color: #FFF;
        font-size: 25px;
      }

      .container #content {
        border: dashed 2px #CCC;
        padding: 10px;
      }

      #reset {
        padding: 5px 10px;
        background: #4CAF50;
        border: none;
        color: #FFF;
        cursor: pointer;
      }

      #reset:hover {
        color: #4CAF50;
        background: #FFF;
      }

      #viewContent table {
        width: 100%;
      }

      #viewContent table tr {
        height: 80px;
        background: darkcyan;
      }

      #viewContent table tr td {
        width: 50%;
        padding-left: 5px;
      }

      #viewContent table tr td img {
        width: 150px;
      }

      #viewContent table tr td span {
        display: block;
      }
    </style>
  </head>

  <body>
    <div class="container">
      <div id="content">
        <h1>Implementing QRCoder in ASP.NET Core - View QR Code Files</h1>
        <h2>
          <a href="http://www.yogihosting.com/category/aspnet-core/">Read the tutorial on YogiHosting » </a>
          <button id="reset" onclick="location=''">Reset »</button>
        </h2>
        <div id="viewContent">
          <table>
            <tbody>
              @foreach (KeyValuePair
              <string, Byte[]> k in Model) {
                <tr>
                  <td>
                    <img src="@String.Format(" data:image/png;base64,{0} ", Convert.ToBase64String(k.Value))" />
                    <span>@k.Key</span>
                  </td>
                </tr>
                }
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </body>

  </html>

This View displays all the qrr files as bitmap images inside a ‘HTML’ table. The below code creates the HTML table:

该视图将所有qrr文件显示为“ HTML”表中的位图图像。 下面的代码创建HTML表:

<table>
  <tbody>
    @foreach (KeyValuePair<string, Byte[]> k in Model)
    {
      <tr>
        <td>
          <img src="@String.Format("data:image/png;base64,{0}", Convert.ToBase64String(k.Value))" />
         <span>@k.Key</span>
        </td>
      </tr>
    }
  </tbody>
</table>
测试代码 (Testing the Code)

Run your application and go to the URL — ‘http://localhost:50755/QRCoder/ViewFile’ to invoke the ViewFile Action method. You will see all the .qrr files saved in your website.

运行您的应用程序,然后转到URL —“ http://localhost:50755/QRCoder/ViewFile ”以调用ViewFile Action方法。 您将看到所有.qrr文件保存在您的网站中。

See the below image which illustrates it working:

请参见下图,它说明了它的工作原理:

You can download the full code from my GitHub Respositiory.

您可以从我的GitHub Repositiory下载完整的代码

结论 (Conclusion)

I hope you love this repository which will help you to use QRCoder in your ASP.NET Core Project. Make sure you like this repository to show your love to it.

我希望您喜欢这个存储库,它将帮助您在ASP.NET Core项目中使用QRCoder。 确保您喜欢此存储库以表示对它的爱。

If you need any help in ASP.NET Core then let me know in the below comments section.

如果您在ASP.NET Core中需要任何帮助,请在下面的评论部分中告诉我。

I publish 2 web development articles per week. Consider following me and get email notification whenever I publish a new tutorial on Medium. If this post was helpful, please click the clap button for a few times to show your support! It will bring a smile on my face and motivate me to write more for the readers like you.

我每周发表2篇Web开发文章。 每当我在Medium上发布新教程时,请考虑关注我并获得电子邮件通知。 如果此帖子有帮助,请单击拍手按钮几次以表示支持! 它会带给我微笑,并激励我为像您这样的读者写更多的文章。

I have also published another tutorial on freeCodeCamp, if you would like to see it too — How to create a login feature with Bootstrap Modal and jQuery AJAX

如果您也想在FreeCodeCamp上阅读,我也已发布了另一篇教程— 如何使用Bootstrap Modal和jQuery AJAX创建登录功能

Thanks and Happy Coding!

谢谢,祝您编码愉快!

翻译自: https://www.freecodecamp.org/news/how-to-easily-implement-qrcoder-in-asp-net-core-using-c-10c4aa857e84/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值