1.添加包
先使用NuGet包管理器添加ThoughtWorks.QRCoder
2.写代码
引入包
using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.Codec.Data;
二维码工具类
static class QRCoderTools
{
static Bitmap AddWhiteBorder(Bitmap bitmap, int borderSize)
{
Bitmap bmp = new Bitmap(bitmap.Width + borderSize * 2, bitmap.Height + borderSize * 2, bitmap.PixelFormat);
Graphics bg = Graphics.FromImage(bmp);
bg.Clear(Color.White);
bg.DrawImage(bitmap, borderSize, borderSize);
return bmp;
}
/// <summary>
/// 生成二维码
/// </summary>
/// <param name="msg">信息</param>
/// <param name="version">版本 1 ~ 40</param>
/// <param name="pixel">像素点大小</param>
/// <param name="borderSize">白边大小</param>
/// <returns>位图</returns>
public static Bitmap Encode(string msg, int version, int pixel, int borderSize)
{
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
qrCodeEncoder.QRCodeVersion = version;
qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
qrCodeEncoder.QRCodeScale = pixel;
Bitmap bmp = null;
try
{
bmp = qrCodeEncoder.Encode(msg, Encoding.UTF8);
}
catch (System.IndexOutOfRangeException)
{
MessageBox.Show("数据量过大,请调大Version值");
return null;
}
Bitmap qr_code_image = AddWhiteBorder(bmp, borderSize);
bmp.Dispose();
return qr_code_image;
}
/// <summary>
/// 识别二维码
/// </summary>
/// <param name="bmp">包含二维码的图片</param>
/// <returns>二维码内容</returns>
public static string Decode(Bitmap bmp)
{
QRCodeDecoder qrCodeDecoder = new QRCodeDecoder();
QRCodeBitmapImage qrCodeBitmapImage = new QRCodeBitmapImage(bmp);
string ret = string.Empty;
try
{
ret = qrCodeDecoder.decode(qrCodeBitmapImage, Encoding.UTF8);
}
catch (Exception)
{
MessageBox.Show("识别失败");
}
return ret;
}
}
最后
该工具包不能添加图标,若想添加图标可以自行渲染,或者用NuGet添加QRCoder工具,它有添加图标的接口
网友评论