最近做項目遇到產生二維碼的問題,發現網上用的最多的是ThoughtWorks.QRCode和QrCode.Net兩種方式。訪問官網看著例子寫了兩個Demo,使用過程中發現兩個都挺好用的,ThoughtWorks.QRCode的功能更多一些,但是dll檔案有6兆,QrCode.Net只有400多K,大家根據自己的需要選擇吧。附上代碼僅供參考。
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; } |