asp.net(C#)利用QRCode生成二维码

  1. <%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”QRCode.aspx.cs” Inherits=”QRCode” %>
  2. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
  3. <html xmlns=”http://www.w3.org/1999/xhtml”>
  4. <head runat=”server”>
  5.     <title>生成二维码</title>
  6. </head>
  7. <body>
  8.     <form id=”form1″ runat=”server”>
  9.     <div>
  10.         请输入内容:<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
  11.         <br/>
  12.         <asp:Button ID=”Button1″ runat=”server” Text=”生成二维码” onclick=”Button1_Click” />
  13.     </div>
  14.     <div style=”text-align:center”>
  15.         <asp:Image ID=”ImageCode” runat=”server” Visible=”false” />
  16.     </div>
  17.     </form>
  18. </body>
  19. </html>
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. public partial class QRCode : System.Web.UI.Page
  8. {
  9.     protected void Page_Load(object sender, EventArgs e)
  10.     {
  11.     }
  12.     protected void Button1_Click(object sender, EventArgs e)
  13.     {
  14.         string CodeText = TextBox1.Text.Trim();
  15.         if (!string.IsNullOrEmpty(CodeText))
  16.         {
  17.             ImageCode.Visible = true;
  18.             ImageCode.ImageUrl = “GetQRCode.ashx?CodeText=” + CodeText;
  19.         }
  20.     }
  21. }
  1. <%@ WebHandler Language=”C#” Class=”GetQRCode” %>
  2. using System;
  3. using System.Web;
  4. using ThoughtWorks.QRCode.Codec;
  5. using ThoughtWorks.QRCode.Codec.Data;
  6. using ThoughtWorks.QRCode.Codec.Util;
  7. using System.IO;
  8. using System.Text;
  9. public class GetQRCode : IHttpHandler {
  10.     public void ProcessRequest (HttpContext context) {
  11.         String data = context.Request[“CodeText”];
  12.         if (!string.IsNullOrEmpty(data))
  13.         {
  14.             QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
  15.             qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
  16.             qrCodeEncoder.QRCodeScale = 4;
  17.             qrCodeEncoder.QRCodeVersion = 8;
  18.             qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
  19.             System.Drawing.Bitmap image = qrCodeEncoder.Encode(data);
  20.             System.IO.MemoryStream MStream = new System.IO.MemoryStream();
  21.             image.Save(MStream, System.Drawing.Imaging.ImageFormat.Png);
  22.             context.Response.ClearContent();
  23.             context.Response.ContentType = “image/Png”;
  24.             context.Response.BinaryWrite(MStream.ToArray());
  25.         }
  26.         context.Response.Flush();
  27.         context.Response.End();
  28.     }
  29.     public bool IsReusable {
  30.         get {
  31.             return false;
  32.         }
  33.     }
  34. }

标签