C# implement QR code
Required import library
using System;
using System.Drawing;
using System.Text;
using ThoughtWorks.QRCode.Codec; // 第三方类库,C#类库中不存在
Invoke generation methods/functions in an object-oriented way
/// <summary>
/// 生成二维码
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btn_CreateQRCode_Click(object sender, EventArgs e)
{
// str 二维码的内容
CreateQRImg(str);
}
Core code
Call the ThoughtWorks.QRCode.dll
implementation of the two-dimensional code library, to achieve common two-dimensional code
The comments are relatively clear and do not repeat too much
/// <summary>
/// 生成并保存二维码图片的方法
/// </summary>
/// <param name="str">输入的内容</param>
private void CreateQRImg(string str)
{
Bitmap bt;
string enCodeString = str;
//生成设置编码实例
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
//设置二维码的规模 默认 4
qrCodeEncoder.QRCodeScale = 4;
//设置二维码的版本 默认 7
qrCodeEncoder.QRCodeVersion = 7;
//设置错误检验级别 默认为中等
qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
//生成二维码图片
bt = qrCodeEncoder.Encode(enCodeString, Encoding.UTF8);
//二维码图片名称
string filename = DateTime.Now.ToString("[名字最好用时间防重]");
//保存二维码图片在photos路径下
bt.Save(Server.MapPath("~/photos/") + filename + ".jpg");
//图片控件要显示的二维码图片路径
this.img_QRImag.ImageUrl = "~/photos/" + filename + ".jpg";
}
- What I use here is to get the keyboard input value for demonstration
- Practical application
str
should be automatically generated values ThoughtWorks.QRCode.dll
The class library is a NuGet download to be downloaded by yourself- The project can be downloaded as open source
ps: The QR code is generally a picture, so our main program should be C/S or B/S application