在上一次说了一下二维码相关的基础知识,没看的赶紧看看,很实用:KING_C#学习之QRCode二维码(一)——基础知识扫盲
QR二维码的生成与识别在C#语言下有多种实现方式,实际上就是利用不同的类库实现。一般来说有以下几种实现方式:
一、利用ThoughtWorks.QRCode.dll类库实现
1、ThoughtWorks.QRCode简介
ThoughtWorks.QRCode 源码地址:
http://www.codeproject.com/Articles/20574/Open-Source-QRCode-Library
ThoughtWorks.QRCode Github地址:
https://github.com/aaronogan/QR.NET
2、实现例子
在C#中直接引用ThoughtWorks.QRCode.dll 类。
生成二维码方法:
/// <summary>
/// 生成二维码,如果有Logo,则在二维码中添加Logo
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
public Bitmap CreateQRCode(string content)
{
QRCodeEncoder qrEncoder = new QRCodeEncoder();
qrEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE; //编码方式:BYTE 能支持中文,ALPHA_NUMERIC 扫描出来的都是数字
qrEncoder.QRCodeScale = Convert.ToInt32(txtSize.Text); //大小:值越大生成的二维码图片像素越高
qrEncoder.QRCodeVersion = Convert.ToInt32(cboVersion.SelectedValue);//版本
qrEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M; //错误校验、更正等级
try
{
Bitmap qrcode = qrEncoder.Encode(content, Encoding.UTF8);
if (!logoImagepath.Equals(string.Empty))
{
Graphics g = Graphics.FromImage(qrcode);
Bitmap bitmapLogo = new Bitmap(logoImagepath);
int logoSize = Convert.ToInt32(txtLogoSize.Text);
bitmapLogo = new Bitmap(bitmapLogo, new System.Drawing.Size(logoSize, logoSize));
PointF point = new PointF(qrcode.Width / 2 - logoSize / 2, qrcode.Height / 2 - logoSize / 2);
g.DrawImage(bitmapLogo, point);
}
return qrcode;
}
catch (IndexOutOfRangeException ex)
{
MessageBox.Show("超出当前二维码版本的容量上限,请选择更高的二维码版本!", "系统提示");
return new Bitmap(100, 100);
}
catch (Exception ex)
{
MessageBox.Show("生成二维码出错!", "系统提示");
return new Bitmap(100, 100);
}
}
解析二维码方法:
/// <summary>
/// 解析二维码
/// </summary>
public void DecodeQRCode()
{
if (bimg == null)
{
MessageBox.Show("请先打开一张二维码图片!", "系统提示");
return;
}
QRCodeDecoder qrDecoder = new QRCodeDecoder();
QRCodeImage qrImage = new QRCodeBitmapImage(bimg);
tbDecodeResult.Text = qrDecoder.decode(qrImage, Encoding.UTF8);
}
二、利用QrCode.Net实现
1、QrCode.NET简介
QrCode.Net可以很方便的生成二维码,速度那是相当的快,并且可支持中文,遵从MIT协议。是一个使用C#编写的用于生成二维码图片的类库,使用它可以非常方便的为WinForm、WebForm、WPF、Silverlight和Windows Phone 7应用程序提供二维码编码输出功能。可以将二维码文件导出为eps格式。
项目地址为:http://qrcodenet.codeplex.com
QrCode.Net不再采用ZXing的端口,新的版本将有更好的性能。
测试结果如下(微秒):
输入字符串长度:74个
EC performance 1000 Tests~ QrCode.Net: 3929 ZXing: 5221
同时,QrCode.Net可以对字符串进行分析,决定是否使用UTF-8编码。(比如使用中文的时候。)
2、实现例子:
新建项目添加对Gma.QrCodeNet.Encoding.dll类库的引用,然后引入Gma.QrCodeNet.Encoding命名空间。
using Gma.QrCodeNet.Encoding;
在控制台中输出二维码:
Console.Write(@"Type some text to QR code: ");
string sampleText = Console.ReadLine();
QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
QrCode qrCode = qrEncoder.Encode(sampleText);
for (int j = 0; j < qrCode.Matrix.Width; j++)
{
for (int i = 0; i < qrCode.Matrix.Width; i++)
{
char charToPrint = qrCode.Matrix[i, j] ? '█' : ' ';
Console.Write(charToPrint);
}
Console.WriteLine();
}
Console.WriteLine(@"Press any key to quit.");
Console.ReadKey();
此代码将产生以下输出:
在Graphics上绘制二维码:
const string helloWorld = "Hello World!";
QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
QrCode qrCode = qrEncoder.Encode(helloWorld);
const int moduleSizeInPixels = 5;
Renderer renderer = new Renderer(moduleSizeInPixels, Brushes.Black, Brushes.White);
Panel panel = new Panel();
Point padding = new Point(10,16);
Size qrCodeSize = renderer.Measure(qrCode.Matrix.Width);
panel.AutoSize = false;
panel.Size = qrCodeSize + new Size(2 * padding.X, 2 * padding.Y);
using (Graphics graphics = panel.CreateGraphics())
{
renderer.Draw(graphics, qrCode.Matrix, padding);
}
在WriteableBitmap上绘制二维码:
const string helloWorld = "Hello World!";
QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
QrCode qrCode = new QrCode();
qrEncoder.TryEncode(helloWorld, out qrCode);
const int moduleSizeInPixels = 5;
Renderer renderer = new Renderer(moduleSizeInPixels); //Black&White is default colour for drawing QrCode
//Matrix under qrCode might be null if input string is null or empty. 21 module wide is version 1 QrCode's width.
int pixelSize = qrCode.Matrix == null ? renderer.Measure(21) : renderer.Measure(qrCode.Matrix.Width);
WriteableBitmap wBitmap = new WriteableBitmap(pixelSize, pixelSize, 96, 96, PixelFormats.Gray8, null);
//If wBitmap is null value. renderer will create Gray8 Bitmap as default.
renderer.Draw(wBitmap, qrCode.Matrix); //Default offset position is (0, 0);
//Now you can put wBitmap to Image control's Source or use it to create image file.
如果需要把二维码呈现在WinForm或者WPF应用程序中,可以直接把类库拖入工具箱,然后直接在窗体上拖出控件。
直接把二维码保存到文件:
QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
QrCode qrCode = new QrCode();
qrEncoder.TryEncode(helloWorld, out qrCode);
Renderer renderer = new Renderer(5, Brushes.Black, Brushes.White);
renderer.CreateImageFile(qrCode.Matrix, @"c:\temp\HelloWorld.png", ImageFormat.Png);
将二维码写入Stream:
QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
QrCode qrCode = new QrCode();
qrEncoder.TryEncode(helloWorld, out qrCode);
Renderer renderer = new Renderer(5, Brushes.Black, Brushes.White);
MemoryStream ms = new MemoryStream();
renderer.WriteToStream(qrCode.Matrix, ms, ImageFormat.png);
三、利用ZXing.Net实现
1、ZXing.Net简介
下载地址:http://zxingnet.codeplex.com/
zxing.net是.net平台下编解条形码和二维码的工具,使用非常方便。
2、实现例子
二维码生成代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ZXing.QrCode;
using ZXing;
using ZXing.Common;
using ZXing.Rendering;
namespace zxingTest
{
public partial class Form1 : Form
{
EncodingOptions options = null;
BarcodeWriter writer = null;
public Form1()
{
InitializeComponent();
options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = pictureBoxQr.Width,
Height = pictureBoxQr.Height
};
writer = new BarcodeWriter();
writer.Format = BarcodeFormat.QR_CODE;
writer.Options = options;
}
private void buttonQr_Click(object sender, EventArgs e)
{
if (textBoxText.Text == string.Empty)
{
MessageBox.Show("输入内容不能为空!");
return;
}
Bitmap bitmap = writer.Write(textBoxText.Text);
pictureBoxQr.Image = bitmap;
}
}
}
将字符编码时可以指定字符格式;默认为ISO-8859-1英文字符集,但一般移动设备常用UTF-8字符集编码,
可以通过QrCodeEncodingOptions设置编码方式。
如果要生成其他zxing支持的条形码,只要修改BarcodeWriter.Format就可以了。
输入字符串需要符合编码的格式,不然会报错。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ZXing.QrCode;
using ZXing;
using ZXing.Common;
using ZXing.Rendering;
namespace zxingTest
{
public partial class Form1 : Form
{
EncodingOptions options = null;
BarcodeWriter writer = null;
public Form1()
{
InitializeComponent();
options = new EncodingOptions
{
//DisableECI = true,
//CharacterSet = "UTF-8",
Width = pictureBoxQr.Width,
Height = pictureBoxQr.Height
};
writer = new BarcodeWriter();
writer.Format = BarcodeFormat.ITF;
writer.Options = options;
}
private void buttonQr_Click(object sender, EventArgs e)
{
if (textBoxText.Text == string.Empty)
{
MessageBox.Show("输入内容不能为空!");
return;
}
Bitmap bitmap = writer.Write(textBoxText.Text);
pictureBoxQr.Image = bitmap;
}
}
}
解析二维码代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ZXing.QrCode;
using ZXing;
using ZXing.Common;
using ZXing.Rendering;
namespace zxingTest
{
public partial class Form1 : Form
{
BarcodeReader reader = null;
public Form1()
{
InitializeComponent();
reader = new BarcodeReader();
}
private void Form1_DragEnter(object sender, DragEventArgs e)//当拖放进入窗体
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy; //显示拷贝效应
else
e.Effect = DragDropEffects.None;
}
private void Form1_DragDrop(object sender, DragEventArgs e) //当拖放放在窗体上
{
string[] fileNames = (string[])e.Data.GetData(DataFormats.FileDrop, false); //获取文件名
if (fileNames.Length > 0)
{
pictureBoxPic.Load(fileNames[0]); //显示图片
Result result = reader.Decode((Bitmap)pictureBoxPic.Image); //通过reader解码
textBoxText.Text = result.Text; //显示解析结果
}
}
}
}