.net - QR Code generation in ASP.NET MVC -
i wrote basic html helper method emit correct <img> tag take advantage of google's api.  so, on page (assuming aspx view engine) use this:
<%: html.qrcodeimage(request.url.absolutepath) %> <%: html.qrcodeimage("meagre human needs phone read qr codes. ha ha ha.") %>   or if want specify size in pixels (the image square):
<%: html.qrcodeimage(request.url.absolutepath, size: 92) %>   here code:
public static class qrcodehtmlhelper {     /// <summary>     /// produces markup image element displays qr code image, provided google's chart api.     /// </summary>     /// <param name="htmlhelper"></param>     /// <param name="data">the data encoded, string.</param>     /// <param name="size">the square length of resulting image, in pixels.</param>     /// <param name="margin">the width of border surrounds image, measured in rows (not pixels).</param>     /// <param name="errorcorrectionlevel">the amount of error correction build image.  higher error correction comes @ expense of reduced space data.</param>     /// <param name="htmlattributes">optional html attributes include on 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 greater zero.");         if (margin < 0)             throw new argumentoutofrangeexception("margin", margin, "must greater or equal 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 7% erroneous data.</summary>     low,     /// <summary>recovers 15% erroneous data.</summary>     medium,     /// <summary>recovers 25% erroneous data.</summary>     quitegood,     /// <summary>recovers 30% erroneous data.</summary>     high }      
Comments
Post a Comment