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/

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

  1. asp.net core中IHttpContextAccessor和HttpContextAccessor的妙用

    分享一篇文章,关于asp.net core中httpcontext的拓展. 现在,试图围绕HttpContext.Current构建你的代码真的不是一个好主意,但是我想如果你正在迁移一个企业类型的应用 ...

  2. 在asp.net core中使用托管服务实现后台任务

    在业务场景中经常需要后台服务不停的或定时处理一些任务,这些任务是不需要及时响应请求的. 在 asp.net中会使用windows服务来处理. 在 asp.net core中,可以使用托管服务来实现,托 ...

  3. ASP.NET Core中显示自定义错误页面-增强版

    之前的博文 ASP.NET Core中显示自定义错误页面 中的方法是在项目中硬编码实现的,当有多个项目时,就会造成不同项目之间的重复代码,不可取. 在这篇博文中改用middleware实现,并且放在独 ...

  4. 探索ASP.NET Core中的IStartupFilter

    原文:Exploring IStartupFilter in ASP.NET Core 作者:Andrew Lock 译者:Lamond Lu 在本篇博客中,我将介绍一下IStartupFilter, ...

  5. 如何简单的在 ASP.NET Core 中集成 JWT 认证?

    前情提要:ASP.NET Core 使用 JWT 搭建分布式无状态身份验证系统 文章超长预警(1万字以上),不想看全部实现过程的同学可以直接跳转到末尾查看成果或者一键安装相关的 nuget 包 自上一 ...

  6. 在 ASP.NET Core 中集成 Skywalking APM

    前言 大家好,今天给大家介绍一下如何在 ASP.NET Core 项目中集成 Skywalking,Skywalking 是 Apache 基金会下面的一个开源 APM 项目,有些同学可能会 APM ...

  7. .ASP NET Core中缓存问题案例

    本篇博客中,我将描述一个关于会话状态(Session State)的问题, 这个问题我已经被询问了好几次了. 问题的场景 创建一个新的ASP.NET Core应用程序 一个用户在会话状态中设置了一个字 ...

  8. ASP.NET Core 中文文档 第三章 原理(13)管理应用程序状态

    原文:Managing Application State 作者:Steve Smith 翻译:姚阿勇(Dr.Yao) 校对:高嵩 在 ASP.NET Core 中,有多种途径可以对应用程序的状态进行 ...

  9. NLog在asp.net core中的应用

    Asp.net core中,自带的Log是在当selfhost运行时,在控制台中输出,不便于查阅,如果用一个log架框,把日志持久化,便于查询. NLog是一个免费的日志记录框架,专门为.net平台下 ...

最新文章

  1. 第2次作业+105032014158
  2. 1 张图,拆解阿里 P8高级架构师必会技术栈!
  3. 这怕是我看过的最好的关于 “ 拜占庭将军问题 ” 的文章
  4. typescript或javascript深拷贝Object json
  5. xCode 安装Mobile Device Framework出错的问题的解决方法
  6. 当直播电商用上 AI 实时翻译,歪果仁也能听懂李佳琦
  7. druid链接mysql-proxy_MySQL读写分离之mysql-proxy
  8. Solr删除managedschema
  9. PPT中均匀分布各图形(水平或垂直)
  10. 写给大家看的设计模式
  11. h5页面编写注意事项,自己遇到的小问题。
  12. anaconda利用sns或plt画图中文乱码问题
  13. FishC笔记—15 讲 字符串:格式化
  14. matlab lbp特征,lbp特征(lbp纹理特征提取)
  15. 深度学习----GAN(生成对抗神经网络)原理解析
  16. 证件照人像与背景分离(Pythoncv)
  17. cf四大战区合区列表?
  18. linux服务器运维巡检脚本,linux服务器巡检脚本
  19. html转图片 workflow,用 Workflow + Day one 给未来的自己做时间履历 | Matrix 精选
  20. 基本矩阵、本质矩阵和单应矩阵

热门文章

  1. hbase shell编码显示中文
  2. React 事件 4
  3. 不用任何第三方,写一个RTMP直播推流器
  4. 『参考』.net CF组件编程(4)——为自定义组件添加工具箱图标!
  5. python之XML文件解析
  6. Python统计字符串中的中英文字符、数字空格,特殊字符
  7. 历史 history
  8. ios开发日记- 5 屏幕截图
  9. powerDesign设计随笔
  10. wifidog接口文档(转)