最近看到滿大街的二維碼掃碼有驚喜,對二維碼也有過一些了解,想看看到底是什麼原理,在網上找了一些資料,自己弄了一個實例,采用的是MVC,貼出來分享一下
Controller
public ActionResult QRCodView() { return View(); }
1 <div class="col-md-4"> 2 <h2>一維碼生成</h2> 3 <div><input type="number" maxlength="24" placeholder="請輸入24位數字" id="text1" class="form-control" /><i id="btnGO1" class="button btn-primary h6">生成一維碼</i></div> 4 <img id="BarCod" src="~/Image/e78b58d4-c4d4-4561-a1a0-854170419f73.jpg" class="img-thumbnail" /> 5 </div> View 1 $("#btnGO1").click(function () { 2 $.post("/Data/Create", { context: $("#text1").val() }, function (d) { 3 $("#BarCod").attr("src", d); 4 }); 5 }); JS代碼
//一維碼生成 public string Create() { string context = Request.Form["context"]; string imgPath = CommCor.BarCodeUnit.CreateBarCode(context, Server.MapPath("~/TempFiled/")); return "/TempFiled/" + imgPath; }//引用命名空間 using ZXing; using System.Drawing; using ZXing.QrCode; using ZXing.Common; using System.Text.RegularExpressions; using System.Drawing.Imaging; using ZXing.QrCode.Internal; using System.IO; /// <summary> /// 一維碼生成 /// </summary> /// <param name="contents"></param> public static string CreateBarCode(string contents, string tempPath) { EncodingOptions options = null; BarcodeWriter writer = null; options = new EncodingOptions { Width = 200, Height = 200 }; writer = new BarcodeWriter(); writer.Format = BarcodeFormat.ITF; writer.Options = options; Bitmap bitmap = writer.Write(contents); string fileName = Guid.NewGuid().ToString() + ".png"; bitmap.Save(tempPath + fileName); return fileName; } 一維碼生成核心代碼
效果如上圖