Подтвердить что ты не робот

Генерация QR-кода в ASP.NET MVC

Есть ли .NET API, который генерирует QR-коды, такие как этот?

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

Я бы хотел отобразить их на страницах, которые, как я ожидаю, мои пользователи будут распечатывать.

4b9b3361

Ответ 1

Я написал базовый HTML-помощник, чтобы исправить правильный тег <img>, чтобы воспользоваться Google API. Итак, на вашей странице (предполагая, что ASPX-движок просмотра) используйте что-то вроде этого:

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

Или, если вы хотите указать размер в пикселях (изображение всегда квадратное):

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

Вот код:

public static class QRCodeHtmlHelper
{
    /// <summary>
    /// Produces the markup for an image element that displays a QR Code image, as provided by Google 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
}

Ответ 2

Один из вариантов заключается в использовании API Google Chart Server для этого, как это.

Например, здесь QR-код для этой самой страницы...

3793799

Не требуется код:)

Ответ 3

Быстрый поиск дает много библиотек QRCode (все они коммерческие, кроме первого):

Ответ 5

Существует также пакет Nuget - QRCodeHelper, который основан на Codeplex QRCode Helper.