Thursday, March 17, 2016

Generate and display QR code image using QR Code library in asp.net

In this article I am going to explain how to generate and display QR code image using QR Code library in asp.net (C#, VB.net)
Generate and display QR code image using QR Code library in asp net


Implementation :

HTML Markup:

 <fieldset style="width:30%">
        <legend>Generate QR Code Example</legend>
        <table>
        <tr><td>Enter URL OR Text:</td><td><asp:TextBox ID="txturl" runat="server"></asp:TextBox></td></tr>
        <tr><td colspan="2"><asp:Image runat="server" ID="QRImage" /></td></tr>
        <tr><td></td><td></td></tr>
        <tr><td></td><td><asp:Button ID="btnsubmit"
            runat="server" Text="Generate QR Code"/></td></tr>
        </table>
        </fieldset>

To install Qr Code library, run the following command in the Package Manager Console
Install-Package MessagingToolkit.QRCode

Add the namespace:
C# code:
using MessagingToolkit.QRCode.Codec;
using MessagingToolkit.QRCode.Codec.Data;

using System.Drawing;
using System.Drawing.Imaging;

VB.net code:
Imports MessagingToolkit.QRCode.Codec
Imports MessagingToolkit.QRCode.Codec.Data
Imports System.Drawing
Imports System.Drawing.Imaging

On button click write the below given code:
C# code:
protected void btnsubmit_Click(object sender, EventArgs e)
    {
        try
        {
        QRCodeEncoder encoder = new QRCodeEncoder();
        encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;
        encoder.QRCodeScale = 10;
        Bitmap img = encoder.Encode(txturl.Text);
        img.Save(Server.MapPath("image/") + "qrimage.png", ImageFormat.Png);
        QRImage.ImageUrl = "image/qrimage.png";      
        }
        catch(Exception ex)
        {
        }
    }

VB.net code:
   Protected Sub btnsubmit_Click(sender As Object, e As System.EventArgs) Handles btnsubmit.Click
        Dim encoder As New QRCodeEncoder()
        encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H
        encoder.QRCodeScale = 10
        Dim img As Bitmap = encoder.Encode(txturl.Text)
        img.Save(Server.MapPath("image/") + "qrimage.png", ImageFormat.Png)
        QRImage.ImageUrl = "image/qrimage.png"
    End Sub


1 comment:

  1. saludos, y si quisiera cambiar el color del QR cual seria el codigo

    ReplyDelete