详解ASP.NET 生成二维码实例(采用ThoughtWorks.QRCode和QrCode.Net两种方式)
最近做项目遇到生成二维码的问题,发现网上用的最多的是ThoughtWorks.QRCode和QrCode.Net两种方式。访问官网看着例子写了两个Demo,使用过程中发现两个都挺好用的,ThoughtWorks.QRCode的功能更多一些,但是dll文件有6兆,QrCode.Net只有400多K,大家根据自己的需要选择吧。附上代码仅供参考。并且提供VS2013写的一个Demo提供给大家免费下载。如有疑问欢迎交流。
ThoughtWorks.QRCode:[code]private void CreateQrcode(string nr)
{
Bitmap bt;
string enCodeString = nr;
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
bt = qrCodeEncoder.Encode(enCodeString, Encoding.UTF8);
string filename = DateTime.Now.ToString("yyyymmddhhmmss");
string path = Server.MapPath("~/image/") + filename + ".jpg";
Response.Write(path);
bt.Save(path);
this.Image1.ImageUrl = "~/image/" + filename + ".jpg";
}[/code]QrCode.Net:[code]protected void Button1_Click(object sender, EventArgs e)
{
using (var ms = new MemoryStream())
{
string stringtest = "中国inghttp://www.baidu.com/mvc.test?&";
GetQRCode(stringtest, ms);
Response.ContentType = "image/Png";
Response.OutputStream.Write(ms.GetBuffer(), 0, (int)ms.Length);
Image img = Image.FromStream(ms);
string filename = DateTime.Now.ToString("yyyymmddhhmmss");
string path = Server.MapPath("~/image/") + filename + ".png";
img.Save(path);
Response.End();
}
}[/code][code]/// <summary>
/// 获取二维码
/// </summary>
/// <param name="strContent">待编码的字符</param>
/// <param name="ms">输出流</param>
///<returns>True if the encoding succeeded, false if the content is empty or too large to fit in a QR code</returns>
public static bool GetQRCode(string strContent, MemoryStream ms)
{
ErrorCorrectionLevel Ecl = ErrorCorrectionLevel.M; //误差校正水平
string Content = strContent;//待编码内容
QuietZoneModules QuietZones = QuietZoneModules.Two; //空白区域
int ModuleSize = 12;//大小
var encoder = new QrEncoder(Ecl);
QrCode qr;
if (encoder.TryEncode(Content, out qr))//对内容进行编码,并保存生成的矩阵
{
var render = new GraphicsRenderer(new FixedModuleSize(ModuleSize, QuietZones));
render.WriteToStream(qr.Matrix, ImageFormat.Png, ms);
}
else
{
return false;
}
return true;
}[/code]下面是下载地址:[url=http://xiazai.jb51.net/201612/yuanma/qrcode_jb51.zip]demo[/url]
.NET 二维码生成(ThoughtWorks.QRCode)
引用ThoughtWorks.QRCode.dll (源代码里有)1、简单二维码生成及解码代码:
//生成二维码方法一
[code] private void CreateCode_Simple(string nr)
{
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
qrCodeEncoder.QRCodeScale = 4;
qrCodeEncoder.QRCodeVersion = 8;
qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
//System.Drawing.Image image = qrCodeEncoder.Encode("4408810820 深圳-广州 小江");
System.Drawing.Image image = qrCodeEncoder.Encode(nr);
string filename = DateTime.Now.ToString("yyyymmddhhmmssfff").ToString() + ".jpg";
string filepath = Server.MapPath(@"~\Upload") + "\\" + filename;
System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
fs.Close();
image.Dispose();
//二维码解码
var codeDecoder = CodeDecoder(filepath);
}
/// <summary>
/// 二维码解码
/// </summary>
/// <param name="filePath">图片路径</param>
/// <returns></returns>
public string CodeDecoder(string filePath)
{
if (!System.IO.File.Exists(filePath))
return null;
Bitmap myBitmap = new Bitmap(Image.FromFile(filePath));
QRCodeDecoder decoder = new QRCodeDecoder();
string decodedString = decoder.decode(new QRCodeBitmapImage(myBitmap));
return decodedString;
}[/code]
2、源代码演示,相对复杂的生成方式:
界面效果:
[img]https://images0.cnblogs.com/blog2015/292326/201506/212209539825834.png[/img]
前端代码:
[code]@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Code</title>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(function () {
$("#createCode").click(function () {
var strData = $("#strData").val();
var level = $("#level").val();
var encoding = $("#encoding").val();
var version = $("#version").val();
var scale = $("#scale").val();
$.post("/home/CreateCode_Choose", { strData: strData, level: level, qrEncoding: encoding, version: version, scale: scale }, function (data) {
$("img").attr("src", data);
});
});
});
</script>
</head>
<body>
<div>
<p>要生成的文字(支持中文):<input id="strData" type="text" value="123456 测试" /></p>
<p>
Encoding:<select id="encoding">
<option value="Byte">Byte</option>
<option value="AlphaNumeric">AlphaNumeric</option>
<option value="Numeric">Numeric</option>
</select>
</p>
<p>
Correction Level:<select id="level">
<option value="M">M</option>
<option value="L">L</option>
<option value="Q">Q</option>
<option value="H">H</option>
</select>
</p>
<p>Version:<input id="version" type="text" value="8" /></p>
<p>scale:<input id="scale" type="text" value="4" /></p>
<img src="" alt="" />
<input id="createCode" type="button" value="生成" />
</div>
</body>
</html>[/code]
后台:
[code]/// 生成二维码
/// </summary>
/// <param name="strData">要生成的文字或者数字,支持中文。如: "4408810820 深圳-广州" 或者:4444444444</param>
/// <param name="qrEncoding">三种尺寸:BYTE ,ALPHA_NUMERIC,NUMERIC</param>
/// <param name="level">大小:L M Q H</param>
/// <param name="version">版本:如 8</param>
/// <param name="scale">比例:如 4</param>
/// <returns></returns>
public ActionResult CreateCode_Choose(string strData, string qrEncoding, string level, int version, int scale)
{
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
string encoding = qrEncoding;
switch (encoding)
{
case "Byte":
qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
break;
case "AlphaNumeric":
qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.ALPHA_NUMERIC;
break;
case "Numeric":
qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.NUMERIC;
break;
default:
qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
break;
}
qrCodeEncoder.QRCodeScale = scale;
qrCodeEncoder.QRCodeVersion = version;
switch (level)
{
case "L":
qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L;
break;
case "M":
qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
break;
case "Q":
qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.Q;
break;
default:
qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;
break;
}
//文字生成图片
Image image = qrCodeEncoder.Encode(strData);
string filename = DateTime.Now.ToString("yyyymmddhhmmssfff").ToString() + ".jpg";
string filepath = Server.MapPath(@"~\Upload") + "\\" + filename;
//如果文件夹不存在,则创建
//if (!Directory.Exists(filepath))
// Directory.CreateDirectory(filepath);
System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
fs.Close();
image.Dispose();
return Content(@"/Upload/" + filename);
}[/code]
[font=Georgia, "]源代码演示下载:[/font][url=http://download.csdn.net/detail/jys1216/8827009]点击下载[/url]
页:
[1]