C# 生成二维码
Posted Jacob Wu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 生成二维码相关的知识,希望对你有一定的参考价值。
方法一、
/// <summary> /// 将信息转化为二维码位图 /// </summary> /// <param name="barcodeText">转化内容</param> /// <returns>转化后的二维码位图</returns> public void BarcodeImage(String barcodeText) { QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(); qrCodeEncoder.QRCodeVersion = 0; Bitmap img = qrCodeEncoder.Encode(barcodeText, Encoding.UTF8);//指定utf-8编码, 支持中文 string httpFileName = @"C:\Users\Administrator\Desktop\ConsoleApplication1\MvcApplication2\"; string fileName = @"\Content\image\" + 123456 + ".jpg"; img.Save(httpFileName + fileName);//保存位图 } /// <summary> /// 解析二维码 /// </summary> /// <param name="bitmap">要解析的二维码位图</param> /// <returns>解析后的字符串</returns> public string QRCodeDecoderUtil(Bitmap bitmap) { QRCodeDecoder decoder = new QRCodeDecoder(); string decodedString = decoder.decode(new QRCodeBitmapImage(bitmap), Encoding.UTF8) ;//指定utf-8编码, 支持中文 return decodedString; }
方法二、
后台:
public FileContentResult BarcodeImage(String barcodeText) { QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(); qrCodeEncoder.QRCodeVersion = 0; Bitmap img = qrCodeEncoder.Encode(barcodeText, Encoding.UTF8);//指定utf-8编码, 支持中文 //string httpFileName = @"C:\Users\Administrator\Desktop\ConsoleApplication1\MvcApplication2\"; //string fileName = @"\Content\image\" + 123456 + ".jpg"; //img.Save(httpFileName + fileName);//保存位图 System.IO.MemoryStream ms = new System.IO.MemoryStream(); img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); return File(ms.GetBuffer(), "image/JPEG"); }
前台:
<script src="~/script/jquery-1.8.2.js"></script> <img src="#" alt="" class="code-img" id="validImg"> <input type="text" id="txt" /> <button id="subId">sub</button> <script> $("#subId").click(function () { $("#validImg").attr("src", "/Home/BarcodeImage?barcodeText=" + $("#txt").val()); }) </script>
以上是关于C# 生成二维码的主要内容,如果未能解决你的问题,请参考以下文章