在网上找了很多,都只能生成网址,不能生成名片二维码,于是自己动手。
第一步,写视图界面,主要代码如下:
名片二维码工具
第二步,写控制器,处理form的post请求。主要是处理vcard的字符串和生成png图片。主要代码:
[HttpPost] public ActionResult MakeQrCode() { string username = Request.Form["Username"]; string phone = Request.Form["Phone"]; StringBuilder Vcard = new StringBuilder(); Vcard.Append("BEGIN:VCARD"); Vcard.Append("FN:").Append(username).Append(";"); Vcard.Append("ORG:").Append("CVTE").Append(";"); Vcard.Append("TEL;WORK;VOICE:").Append(phone).Append(";"); //Vcard.Append("TEL;TYPE=VOICE,WORK;VALUE=text:").Append(phone).Append(";"); Vcard.Append("END:VCARD"); //结束 //这样写也可以 StringBuilder Vcard1 = new StringBuilder(); Vcard1.Append("BEGIN:VCARD"); Vcard1.Append(System.Environment.NewLine); Vcard1.Append("VERSION:3.0") ; Vcard1.Append(System.Environment.NewLine); Vcard1.Append("FN:" + username) ; //Vcard1.Append("TEL;WORK;VOICE:" + phone ); Vcard1.Append(System.Environment.NewLine); Vcard1.Append("TEL;TYPE=VOICE,WORK;VALUE=text:" + phone) ; Vcard1.Append(System.Environment.NewLine); Vcard1.Append("ORG:CVTE") ; Vcard1.Append(System.Environment.NewLine); Vcard1.Append("END:VCARD"); //string vcard = @"BEGIN:VCARD" + System.Environment.NewLine + "VERSION:3.0" + System.Environment.NewLine + "FN:" + username + "CVTE" + System.Environment.NewLine + "TEL;TYPE=VOICE,WORK;VALUE=text:" + phone + "" + System.Environment.NewLine + "END:VCARD"; //string imageUrl = string.Format(@"",Server.HtmlEncode( vcard) ); string imageUrl = string.Format(@"", Server.HtmlEncode(Vcard.ToString())); return BarcodeImage(Vcard1.ToString()); } [HttpPost] public MvcHtmlString MakeQrURLCode() { string url = Request.Form["URL"]; string imageUrl = ""; return new MvcHtmlString(imageUrl); } public ActionResult BarcodeImage(String barcodeText) { QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = new QrCode(); qrEncoder.TryEncode(barcodeText, out qrCode); GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(4, QuietZoneModules.Four), Brushes.Black, Brushes.White); Stream memoryStream = new MemoryStream(); renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, memoryStream); memoryStream.Position = 0; var resultStream = new FileStreamResult(memoryStream, "image/png"); resultStream.FileDownloadName = "cvteQR.png"; return resultStream; }
完整代码下载: