2010-09-25 27 views
28

¿Existe una API .NET que genere QR Codes como esta?Generación de código QR en ASP.NET MVC

Meagre human needs a phone to read QR codes. Ha ha ha.

me gustaría mostrar éstos en las páginas que espero que mis usuarios imprimir a cabo.

+4

El código QR dice: "Un humano escaso necesita un teléfono para leer los códigos QR. Ja, ja, ja. "Encantador. :) –

+2

No sé por qué esto se estableció como fuera de tema. Encuentro que está exactamente sobre el tema ...:/ –

Respuesta

53

escribí un método básico de ayuda HTML para emitir la <img> etiqueta correcta para aprovechar las API de Google. Así, en su página (suponiendo ASPX vista del motor) usar algo como esto:

<%: Html.QRCodeImage(Request.Url.AbsolutePath) %> 
<%: Html.QRCodeImage("Meagre human needs a phone to read QR codes. Ha ha ha.") %> 

O si desea especificar el tamaño en píxeles (la imagen es siempre cuadrada):

<%: Html.QRCodeImage(Request.Url.AbsolutePath, size: 92) %> 

Aquí está el código:

public static class QRCodeHtmlHelper 
{ 
    /// <summary> 
    /// Produces the markup for an image element that displays a QR Code image, as provided by Google's chart API. 
    /// </summary> 
    /// <param name="htmlHelper"></param> 
    /// <param name="data">The data to be encoded, as a string.</param> 
    /// <param name="size">The square length of the resulting image, in pixels.</param> 
    /// <param name="margin">The width of the border that surrounds the image, measured in rows (not pixels).</param> 
    /// <param name="errorCorrectionLevel">The amount of error correction to build into the image. Higher error correction comes at the expense of reduced space for data.</param> 
    /// <param name="htmlAttributes">Optional HTML attributes to include on the image element.</param> 
    /// <returns></returns> 
    public static MvcHtmlString QRCode(this HtmlHelper htmlHelper, string data, int size = 80, int margin = 4, QRCodeErrorCorrectionLevel errorCorrectionLevel = QRCodeErrorCorrectionLevel.Low, object htmlAttributes = null) 
    { 
     if (data == null) 
      throw new ArgumentNullException("data"); 
     if (size < 1) 
      throw new ArgumentOutOfRangeException("size", size, "Must be greater than zero."); 
     if (margin < 0) 
      throw new ArgumentOutOfRangeException("margin", margin, "Must be greater than or equal to zero."); 
     if (!Enum.IsDefined(typeof(QRCodeErrorCorrectionLevel), errorCorrectionLevel)) 
      throw new InvalidEnumArgumentException("errorCorrectionLevel", (int)errorCorrectionLevel, typeof (QRCodeErrorCorrectionLevel)); 

     var url = string.Format("http://chart.apis.google.com/chart?cht=qr&chld={2}|{3}&chs={0}x{0}&chl={1}", size, HttpUtility.UrlEncode(data), errorCorrectionLevel.ToString()[0], margin); 

     var tag = new TagBuilder("img"); 
     if (htmlAttributes != null) 
      tag.MergeAttributes(new RouteValueDictionary(htmlAttributes)); 
     tag.Attributes.Add("src", url); 
     tag.Attributes.Add("width", size.ToString()); 
     tag.Attributes.Add("height", size.ToString()); 

     return new MvcHtmlString(tag.ToString(TagRenderMode.SelfClosing)); 
    } 
} 

public enum QRCodeErrorCorrectionLevel 
{ 
    /// <summary>Recovers from up to 7% erroneous data.</summary> 
    Low, 
    /// <summary>Recovers from up to 15% erroneous data.</summary> 
    Medium, 
    /// <summary>Recovers from up to 25% erroneous data.</summary> 
    QuiteGood, 
    /// <summary>Recovers from up to 30% erroneous data.</summary> 
    High 
} 
+1

+1 para la cadena de muestra divertida – usr

+1

+1 de exactamente lo que estaba buscando. – Gallen

+1

Tenga en cuenta que según este developers.google.com/chart/infographics Código QR de Google Chart está en desuso – Alexandre

28

Una opción es usar el Google Chart Server API para hacerlo, like this.

Por ejemplo, aquí está el código QR para esta misma página ...

No se requiere código :)

+1

Gracias. Encontré esta API poco después de publicarla y la envolví con un método de ayuda ASP.NET MVC, ya que la voy a llamar desde varios lugares. El código se publica en una respuesta, en caso de que ayude a otra persona. –

+1

actualización rápida de url: http://code.google.com/apis/chart/infographics/docs/qr_codes.html – benpage

+0

@benpage: Gracias, hecho. –

7
+0

Gracias. El primer enlace parece interesante. Por cierto, ese enlace está desactualizado (voy a editar tu respuesta.) –