最近做项目遇到生成二维码的问题,发现网上用的最多的是ThoughtWorks.QRCode和QrCode.Net两种方式。访问官网看着例子写了两个Demo,使用过程中发现两个都挺好用的,ThoughtWorks.QRCode的功能更多一些,但是dll文件有6兆,QrCode.Net只有400多K,大家根据自己的需要选择吧。附上代码仅供参考。
并且提供VS2013写的一个Demo提供给大家免费下载。如有疑问欢迎交流。
ThoughtWorks.QRCode:
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";
}
QrCode.Net:
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();
}
}
/// <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;
}
下面是下载地址: