ASP.NET实现二维码(QRCode)的创建和读取
二、ASPX页面(两个jquery的js文件请自行去官网下载):
[html]
<html xmlns="http://www.w3.org/1999/xhtml">
<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>
<p>
<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>
</p>
</body>
</html>
三、test.js文件
[javascript]
$(document).ready(function ()
{
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,没有判断目录是否存在等问题,请自行建立或者更改代码。
[csharp]
using System;
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;
}
}
}
上一篇: 10进制整数转62进制的函数
下一篇: MySQL各种索引类型的操作讲解