ASP.NET实现二维码(QRCode)的创建和读取实例
本文实例讲述了asp.net实现二维码(qrcode)的创建和读取方法。分享给大家供大家参考。具体分析如下:
概述:
qr二维码比其他二维码相比,具有识读速度快、数据密度大、占用空间小的优势。qr码的三个角上有三个寻象图形,使用ccd识读设备来探测码的位置、大小、倾斜角度、并加以解码,实现360读高速识读。每秒可以识读30个含有100个字符qr码。qr码容量密度 大,可以放入1817个汉字、7089个数字、4200个英文字母。qr码用数据压缩方式表示汉字,仅用13bit即可表示一个汉字,比其他二维条码表示 汉字的效率提高了20%。qr具有4个等级的纠错功能,即使破损或破损也能够正确识读。qr码抗弯曲的性能强,通过qr码中的每隔一定的间隔配置有校正图 形,从码的外形来求得推测校正图形中心点与实际校正图形中心点的误差来修正各个模快的中心距离,即使将qr码贴在弯曲的物品上也能够快速识读。qr码可以分割成16个qr码,可以一次性识读数个分割码,适应于印刷面积有限及细长空间印刷的需要。此外微型qr码可以在1厘米的空间内放入35个数字或9个汉字 或21个英文字母,适合对小型电路板对id号码进行采集的需要。
qrcode点击此处本站下载(支持中文)
一、项目引用qrcode的dll文件(thoughtworks.qrcode.dll)
二、aspx页面(两个jquery的js文件请自行去官网下载):
<head runat="server">
<title>二维码工具测试</title>
<script type="text/javascript" src="../../scripts/jquery/jquery-1.6.2.js"></script>
<script type="text/javascript" src="../../scripts/jquery/jquery.form.js"></script>
<script type="text/javascript" src="js/test.js"></script>
<style type="text/css">
.style1
{
width: 100%;
}
#txt_qr
{
width: 632px;
}
</style>
</head>
<body>
<div>
<table class="style1">
<tr>
<td>
输入文字:
</td>
<td>
<input type="text" id="txt_qr" name="txt_qr" />
</td>
</tr>
<tr>
<td>
二维码图片
</td>
<td>
<img id="qrimg" alt="二维码图片" />
</td>
</tr>
<tr>
<td>
生成选项
</td>
<td>
encoding:<select id="encoding">
<option value="byte">byte</option>
<option value="alphanumeric">alphanumeric</option>
<option value="numeric">numeric</option>
</select>
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>
version:<input id="txt_ver" type="text" value="7" />(1-40) size:<input id="txt_size"
type="text" value="4" />
</td>
</tr>
<tr>
<td colspan="4">
<input type="button" onclick="getqrimg();" value="生成二维码" />
</td>
</tr>
<tr>
<td>
<form id="qrform" action="ashx/test.ashx" method="post" enctype="multipart/form-data">
<input type="file" id="file_qr" name="file_qr" /><input type="submit" value="读取二维码" />
</form>
</td>
<td colspan="1">
<img id="img_qr" alt="要读取的图片" /><br />
<input id="txt_readqr" type="text" />
</td>
</tr>
</table>
</div>
</body>
</html>
三、test.js文件
{
var options = {
beforesubmit: showrequest,
success: showresponse,
datatype: 'json',
clearform: true,
error: function (request, message, ex)
{
alert('错误:' + message);
}
};
$('#qrform').ajaxform(options);
});
function showrequest(formdata, jqform, options)
{
return true;
}
function showresponse(responsetext, statustext, xhr, $form)
{
if (responsetext[0].count == 0)
{
alert(responsetext[0].list[0].error);
return false;
}
$("#img_qr").attr("src", responsetext[0].list[0].imgurl);
$("#txt_readqr").val(responsetext[0].list[0].qrtext);
return false;
}
function getqrimg()
{
var txt_qr = escape($.trim($("#txt_qr").val()));
var qrencoding = $("#encoding").val(); ;
var level = $("#level").val(); ;
var txt_ver = $("#txt_ver").val(); ;
var txt_size = $("#txt_size").val(); ;
$.ajax({
type: "get",
data: "cmd=set&txt_qr=" + txt_qr + "&qrencoding=" + qrencoding + "&level=" + level + "&txt_ver=" + txt_ver + "&txt_size=" + txt_size,
url: "ashx/test.ashx",
datatype: 'text',
beforesend: function (x)
{
x.setrequestheader("content-type", "application/x-www-form-urlencoded; charset=utf-8");
},
success: function (json)
{
var dataobj = eval(json);
$("#qrimg").attr("src", dataobj[0].list[0].imgurl);
return false;
},
error: function (request, message, ex)
{
alert("错误:" + message);
}
});
}
四、test.ashx,没有判断目录是否存在等问题,请自行建立或者更改代码。
using system.web;
using system.drawing;
using system.drawing.imaging;
using system.text;
using system.text.regularexpressions;
using thoughtworks.qrcode.codec;
using thoughtworks.qrcode.codec.data;
using thoughtworks.qrcode.codec.util;
public class test : ihttphandler
{
public void processrequest(httpcontext context)
{
context.response.contenttype = "text/plain";
string cmd = context.request["cmd"] == null ? "get" : context.request["cmd"].tostring();
string filename = string.empty;
string filepath = string.empty;
switch (cmd)
{
case "get":
if (context.request.files.count > 0)
{
for (int j = 0; j < context.request.files.count; j++)
{
filename = guid.newguid().tostring() + "_tmp.jpg";
filepath = context.server.mappath(@"~\utilty\qrcode\upload") + "\\" + filename;
string qrdecode = string.empty;
httppostedfile uploadfile = context.request.files[j];
uploadfile.saveas(filepath);
qrcodedecoder decoder = new qrcodedecoder();
bitmap bm = new bitmap(filepath);
qrdecode = decoder.decode(new qrcodebitmapimage(bm));
bm.dispose();
context.response.write("[{\"count\":1,\"list\":[{\"imgurl\":\"upload/" + filename + "\",\"qrtext\":\"" + qrdecode + "\"}]}]");
}
}
else
{
context.response.write("[{\"count\":0,\"list\":[{\"error\":\"没有上传文件\"}]}]");
}
break;
case "set":
string txt_qr =convertogb(context.request["txt_qr"].tostring().trim(), 16);
string qrencoding = context.request["qrencoding"].tostring();
string level = context.request["level"].tostring();
string txt_ver = context.request["txt_ver"].tostring();
string txt_size = context.request["txt_size"].tostring();
qrcodeencoder qrcodeencoder = new qrcodeencoder();
string encoding = qrencoding;
if (encoding == "byte")
{
qrcodeencoder.qrcodeencodemode = qrcodeencoder.encode_mode.byte;
}
else if (encoding == "alphanumeric")
{
qrcodeencoder.qrcodeencodemode = qrcodeencoder.encode_mode.alpha_numeric;
}
else if (encoding == "numeric")
{
qrcodeencoder.qrcodeencodemode = qrcodeencoder.encode_mode.numeric;
}
try
{
int scale = convert.toint16(txt_size);
qrcodeencoder.qrcodescale = scale;
}
catch (exception ex)
{
return;
}
try
{
int version = convert.toint16(txt_ver);
qrcodeencoder.qrcodeversion = version;
}
catch (exception ex)
{
return;
}
string errorcorrect = level;
if (errorcorrect == "l")
qrcodeencoder.qrcodeerrorcorrect = qrcodeencoder.error_correction.l;
else if (errorcorrect == "m")
qrcodeencoder.qrcodeerrorcorrect = qrcodeencoder.error_correction.m;
else if (errorcorrect == "q")
qrcodeencoder.qrcodeerrorcorrect = qrcodeencoder.error_correction.q;
else if (errorcorrect == "h")
qrcodeencoder.qrcodeerrorcorrect = qrcodeencoder.error_correction.h;
image image;
string data = txt_qr;
image = qrcodeencoder.encode(data);
filename = guid.newguid().tostring() + ".jpg";
filepath = context.server.mappath(@"~\utilty\qrcode\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();
context.response.write("[{\"count\":1,\"list\":[{\"imgurl\":\"upload/" + filename + "\"}]}]");
//context.response.write(@"upload\" + filename);
break;
}
}
/// <summary>
/// 10进制或16进制转换为中文
/// </summary>
/// <param name="name">要转换的字符串</param>
/// <param name="frombase">进制(10或16)</param>
/// <returns></returns>
public string convertogb(string text, int frombase)
{
string value = text;
matchcollection mc;
system.text.stringbuilder sb = new system.text.stringbuilder();
switch (frombase)
{
case 10:
matchcollection mc1 = regex.matches(text, @"([\d]{5})", regexoptions.compiled | regexoptions.ignorecase);
foreach (match _v in mc1)
{
string w = _v.value.substring(2);
w = convert.tostring(int.parse(w), 16);
byte[] c = new byte[2];
string ss = w.substring(0, 2);
int c1 = convert.toint32(w.substring(0, 2), 16);
int c2 = convert.toint32(w.substring(2), 16);
c[0] = (byte)c2;
c[1] = (byte)c1;
sb.append(encoding.unicode.getstring(c));
}
value = sb.tostring();
break;
case 16:
mc = regex.matches(text, @"\\u([\w]{2})([\w]{2})", regexoptions.compiled | regexoptions.ignorecase);
if (mc != null && mc.count > 0)
{
foreach (match m2 in mc)
{
string v = m2.value;
string w = v.substring(2);
byte[] c = new byte[2];
int c1 = convert.toint32(w.substring(0, 2), 16);
int c2 = convert.toint32(w.substring(2), 16);
c[0] = (byte)c2;
c[1] = (byte)c1;
sb.append(encoding.unicode.getstring(c));
}
value = sb.tostring();
}
break;
}
return value;
}
public bool isreusable
{
get
{
return false;
}
}
}
效果如下图所示:
ps:感兴趣的朋友还可参考本站二维码工具:
希望本文所述对大家的asp.net程序设计有所帮助。