使用Zxing 一维码
最近看到满大街的二维码扫码有惊喜,对二维码也有过一些了解,想看看到底是什么原理,在网上找了一些资料,自己弄了一个实例,采用的是MVC,贴出来分享一下
一维码生成
Controller
public ActionResult QRCodView() { return View(); }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 $("#btnGO1").click(function () { 2 $.post("/Data/Create", { context: $("#text1").val() }, function (d) { 3 $("#BarCod").attr("src", d); 4 }); 5 });
//一维码生成 public string Create() { string context = Request.Form["context"]; string imgPath = CommCor.BarCodeUnit.CreateBarCode(context, Server.MapPath("~/TempFiled/")); return "/TempFiled/" + imgPath; }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//引用命名空间 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; }
效果如上图