1.到网上下载 ThoughtWorks.QRCode.dll 到桌面(其他路径也可以,只要你自己知道就行),不用担心,文件很小的。这是生成二维码的dll文件。如果少了后面就没法操作了。
2.控制器
1 using System.Web.Mvc; 2 using ThoughtWorks; 3 using ThoughtWorks.QRCode; 4 using ThoughtWorks.QRCode.Codec; 5 using ThoughtWorks.QRCode.Codec.Data; 6 using System.Drawing; 7 using System.IO; 8 using System.Text; 9 public string CreateQRCode(string text) 10 { 11 QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(); 12 qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE; 13 qrCodeEncoder.QRCodeScale = 4; 14 qrCodeEncoder.QRCodeVersion = 8; 15 qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M; 16 System.Drawing.Image image = qrCodeEncoder.Encode(text, Encoding.UTF8); 17 string targetFilePath = Path.Combine(Request.MapPath("~/image/")); 18 if (!Directory.Exists(targetFilePath))//文件夹不存在的时候创建 19 { 20 Directory.CreateDirectory(targetFilePath); 21 } 22 string filename = DateTime.Now.ToString("yyyymmddhhmmssfff").ToString() + ".jpg"; 23 string filepath = Server.MapPath(@"~/image/") + filename; 24 System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); 25 image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg); 26 27 fs.Close(); 28 image.Dispose(); 29 return filename; 30 }
3.html
1 <div> 2 <table> 3 <tr> 4 <td><img id="imgs" /></td> 5 </tr> 6 <tr> 7 <td><input id="text" /></td> 8 </tr> 9 <tr> 10 <td><button type="button" style="height:30px;width:100px" onclick="generateQRCord(this)">生成二维码</button></td> 11 </tr> 12 </table> 13 </div> 14 15 <script> 16 function generateQRCord(obj) { 17 var text = $("#text").val(); 18 $.post("/Home/CreateQRCode", { text: text }, function (data) { 19 $("#imgs").attr("src", "/image/" + data); 20 }) 21 } 22 </script>