引用DLL文件:ThoughtWorks.QRCode.dll
.net4.0环境
》》》QRcodeHelper.cs 文件源码
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using ThoughtWorks.QRCode;
using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.ExceptionHandler;
using ThoughtWorks.QRCode.Codec.Data;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;
namespace QRcode
{
public class QRcodeHelper
{
/// 生成二维码
/// </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 string 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;
}
//文字生成图片
//strData = HttpUtility.HtmlDecode(strData); // ConverToGB(strData, 16);
Image image = qrCodeEncoder.Encode(strData,Encoding.GetEncoding("UTF-8"));
string filename = DateTime.Now.ToString("yyyymmddhhmmssfff").ToString() + System.Guid.NewGuid().ToString("N").Substring(15) + ".jpg";
string filepath = HttpContext.Current.Server.MapPath(@"~\Upload") + "\\" + filename;
//如果文件夹不存在,则创建
if (!Directory.Exists(HttpContext.Current.Server.MapPath(@"~\Upload")))
Directory.CreateDirectory(HttpContext.Current.Server.MapPath(@"~\Upload"));
//System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
//image.Save(fs, System.Drawing.Imaging.ImageFormat.Png);
//fs.Close();
image.Save(filepath);
image.Dispose();
return string.Concat(@"/Upload/" + filename);
}
/// <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),Encoding.GetEncoding("UTF-8"));
myBitmap.Dispose();
decoder = null;
return decodedString;
}
/// <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;
}
}
}
》》》aspx.c后台代码
//QRcode生成
protected void Button1_Click(object sender, EventArgs e)
{
QRcodeHelper qrhelper = new QRcodeHelper();
//Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
//byte[] arrB = encode.GetBytes(strData.Text);
//string testB = "";
//for(int i=0;i<arrB.Length;i++)
//{
// testB += arrB[i];
//}
string strDatatxt = strData.Text; //HttpUtility.HtmlEncode();
string qrEncodingtxt = encoding.Value;
string leveltxt = level.Value;
int versionint = Convert.ToInt32(version.Value);
int scaleint = Convert.ToInt32(scale.Value);
imgs.Src = qrhelper.CreateCode_Choose(strDatatxt, qrEncodingtxt, leveltxt, versionint, scaleint);
}
//QRcode读取
protected void barcodeUp_Click(object sender, EventArgs e)
{
string path = Server.MapPath("~/Upload/");
bool fileck = false;
if (FileUpload1.HasFile == false)
{
statusp.InnerText = "请选择待读取的二维码图片文件!";
return;
}
else
{
string fileformatcheck = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
string[] checklist = { ".jpg", ".gif", ".png" };
for (int i = 0; i < checklist.Length;i++ )
{
if(fileformatcheck==checklist[i])
{
fileck = true;
break;
}
}
if (!fileck)
{
statusp.InnerText = "请选择图片格式的二维码文件!(jpg,gif,png)";
fileck = false ;
return;
}
if(FileUpload1.PostedFile.ContentLength >1024000)
{
statusp.InnerText = "请选择文件大小1M以内的二维码文件!";
fileck = false;
return;
}
if(fileck)
{
try
{
string filename = DateTime.Now.ToString("yyyymmddhhmmssfff").ToString() + System.Guid.NewGuid().ToString("N").Substring(15) + fileformatcheck;
string fullname = path + filename;
FileUpload1.PostedFile.SaveAs(fullname);
imgUp.Src = string.Concat(@"/Upload/" + filename);
QRcodeHelper qrhelper = new QRcodeHelper();
TextBox1.Text = qrhelper.CodeDecoder(fullname);
qrhelper = null;
statusp.InnerText = "二维码文件导入完成!";
return;
}
catch
{
statusp.InnerText = "二维码文件导入失败!";
return;
}
}
}
}
》》》aspx前台代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="QRcode._Default" CodePage="65001" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>QRcode</title>
</head>
<body>
<form runat="server">
<div >
<center><table style="width:800px;margin:0px 0px">
<tr>
<td style="background-color: lightblue; width: 400px; margin-top: 5px; vertical-align: top">
<p style="font-weight:bold">
要生成的文字(支持中文):<asp:TextBox ID="strData" runat="server" Width="400px" Height="60px" TextMode="MultiLine" Text="" placeholder="请输入待生成二维码的内容" />
<%--<input id="strData1" runat="server" type="text" value="123456 测试" style="height:60px;width:300px" /></p>--%>
</p>
<p>
Encoding:
<select id="encoding" runat="server">
<option value="Byte">Byte</option>
<option value="AlphaNumeric">AlphaNumeric</option>
<option value="Numeric">Numeric</option>
</select>
</p>
<p>
Correction Level:<select id="level" runat="server">
<option value="M">M</option>
<option value="L">L</option>
<option value="Q">Q</option>
<option value="H">H</option>
</select>
</p>
<div style="width: 180px; height: 170px; border: 3px solid blue; text-align: center; padding-top: 15px;float:right">
<img src="" alt="" id="imgs" runat="server" style="width: 150px; height: 150px" />
</div>
<p>Version:<input id="version" type="text" runat="server" value="8" /></p>
<p>scale:<input id="scale" type="text" runat="server" value="4" /></p>
<br /><br />
<asp:Button ID="createCode" runat="server" Text="生成" OnClick="Button1_Click" Height="45px" Width="65px" Font-Size="Large" />
</td>
<td style="background-color: lightgreen; padding-top: 10px; width: 100%; height: 100px">
<p style="text-align: left;font-weight:bold">选择二维码图片(支持中文):</p>
<asp:FileUpload ID="FileUpload1" runat="server" Width="380px" Height="30px" />
<br />
<br />
<div style="text-align:center">
<asp:Button ID="barcodeUp" runat="server" Text="读取" OnClick="barcodeUp_Click" Height="35px" Width="65px" Font-Size="Large" />
</div>
<br />
<br />
<center>
<div style="width: 180px; height: 170px; border: 3px solid blue;text-align:center;padding-top:15px">
<img src="" alt="" id="imgUp" runat="server" style="width: 150px; height: 150px;" />
</div></center>
<br />
<b>二维码读取结果:</b>
<asp:TextBox ID="TextBox1" runat="server" Width="400px" Height="60px" TextMode="MultiLine" Text="" />
<p>※</p><p style="text-align: left; color: red" id="statusp" runat="server"></p>
</td>
</tr>
</table></center>
</div>
<br />
</form>
</body>
</html>
》》》》》》》简版DEMO
在二维码生成解决方案中我们选择ThoughtWorks的QRCode库。
在项目中引入ThoughtWorks.QRCode.dll
此dll在文件夹中可以获得。
引入相关命名空间:
using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.Codec.Data;
根据字符串产生二维码图:
Bitmap generateImg(string link)
{
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
//设置编码测量度
qrCodeEncoder.QRCodeScale = 4;// (值越大生成的二维码图片像素越高)
//设置编码版本
qrCodeEncoder.QRCodeVersion = 0;//版本(注意:设置为0主要是防止编码的字符串太长时发生错误)
//设置编码错误纠正
qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M; //错误效验、错误更正(有4个等级:H-L-M-Q)
Bitmap bmp = qrCodeEncoder.Encode(link,Encoding.UTF8);
return bmp;
}
识别二维码,获取二维码中的字符串信息
string generateText(Image img)
{
string text=null;
try
{
QRCodeDecoder decoder = new QRCodeDecoder();
QRCodeImage qrimg = new QRCodeBitmapImage(new Bitmap(img));
text = decoder.decode(qrimg,Encoding.UTF8);
}
catch
{
MessageBox.Show("无法识别到二维码");
}
return text;
}