1.引入ThoughtWorks.QRCode.dll類庫到程式中
ThoughtWorks.QRCode.dll下載下傳位址
在工程的右邊解決方案中添加引用–>浏覽–>找到下載下傳後存放ThoughtWorks.QRCode.dll路徑,然後選擇ThoughtWorks.QRCode.dll類庫---->确定
2.建立MyQR.cs類 用來生成和解析二維碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using ThoughtWorks.QRCode.Codec;
using System.Drawing;
using ThoughtWorks.QRCode.Codec.Data;
namespace ProductQR
{
public class MyQR
{
/// <summary>
/// 生成二維碼
/// </summary>
/// <param name="barcodeText">文本</param>
/// <returns>圖檔</returns>
public Bitmap BarcodeImage(String barcodeText)
{
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
qrCodeEncoder.QRCodeVersion = 0;
Bitmap img = qrCodeEncoder.Encode(barcodeText, Encoding.UTF8);//指定utf-8編碼, 支援中文
return img;
//string httpFileName = System.Environment.CurrentDirectory;
//string fileName = "/a.jpg";
//img.Save(httpFileName + fileName);//儲存位圖
}
/// <summary>
/// 解析二維碼文本
/// </summary>
/// <param name="bitmap">圖檔對象</param>
/// <returns></returns>
public string QRCodeDecoderUtil(Bitmap bitmap)
{
QRCodeDecoder decoder = new QRCodeDecoder();
string decodedString = "";
try
{
decodedString = decoder.decode(new QRCodeBitmapImage(bitmap), Encoding.UTF8);//指定utf-8編碼, 支援中文
}
catch (Exception e)
{
return "請先生成二維碼!";
}
return decodedString;
}
}
}
測試類Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ProductQR
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MyQR d = new MyQR();
Bitmap b= d.BarcodeImage(textBox1.Text.ToString());
MessageBox.Show("ok!");
pictureBox1.Image = b;
}
private void button2_Click(object sender, EventArgs e)
{
MyQR d = new MyQR();
MessageBox.Show(d.QRCodeDecoderUtil((Bitmap)this.pictureBox1.Image));
}
}
}