Share via

How can I put an image in the middle of a QR code and still make the QR Image readable?

Donald Symmons 3,066 Reputation points
May 1, 2023, 6:22 AM

I have previously asked this question about putting an image in the middle of QR code, but I was not able to get an answer.

I have this code that generates QR code and I want to put a logo in the middle of the QR. This logo, in my case, is read from the database table and is being displayed in an image control on the web form.

*The logo to be put on the QR code is going to be just one logo. I am learning how to create a situation where any signed up user can generate QR code with the user's logo on it. Not necessarily a logo image that is stored in a folder directory.

Currently, I know how to generate a QR code that can be read by a QR code scanner, I just need to learn how to add uniqueness to it by having logo in the middle of the QR code image.

I tried to add the logo image source to the code that generates the QR, but it did not work.

May I please ask, if anybody has an idea how to make this work, bearing in mind that the image to be put in the middle of the QR code is displayed inside an asp image control on the web form?

<div>
            <asp:Image ID="LogoImage" runat="server" />
            <br /><br />
        </div>
        <div>
            <asp:Image ID="QRImage1" runat="server" />
            <br />
        </div>
        <div>
            <asp:Button ID="Button1" runat="server" Text="Generate Code" />
        </div>

C#

protected void Page_Load(object sender, EventArgs e)
    {
        Showdata1();
    }
    public void Showdata1()
    {
        //In this public void, the logo image is read from the database table and displayed on the web form.
        string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(connectionString))
        {
             using (SqlCommand cmd = new SqlCommand("SELECT * FROM myTable WHERE Id = @Id", con))
             {
                  cmd.Parameters.AddWithValue("@Id", Session["user"]);
                  con.Open();
                  SqlDataReader dr = cmd.ExecuteReader();
                   if (dr.Read())
                   {
                      byte[] bytes = (byte[])dr["LogoImage"];
                    LogoImage.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(bytes);
                   }
             }
        }
    }
    public byte[] GenerateQRCode(string url)
    {
        //I tried to use this below line to get the image source.
        byte[] image = Convert.FromBase64String(LogoImage.ImageUrl.Replace("data:image/jpeg;base64,", ""));
        QRCodeEncoder encoder = new QRCodeEncoder();

        Bitmap bi = encoder.Encode(url);
        MemoryStream tmpSteam = new MemoryStream();

        System.Drawing.Image logo = System.Drawing.Image.FromStream(image + LogoImage.ImageUrl);

        int left = (bi.Width - logo.Width) / 2;
        int top = (bi.Width / 2) - (logo.Width / 2);

        Graphics g = Graphics.FromImage(bi);

        g.DrawImage(logo, new Point(left, top));

        bi.Save(tmpSteam, ImageFormat.Jpeg);
        return tmpSteam.ToArray();

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //This button event is to generate the Code, on the click of the button.
        byte[] QRBytes = GenerateQRCode(ToAbsoluteUrl("~/detailspage.aspx") + "?Id=" + Request.QueryString["Id"]);
        QRImage1.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(QRBytes);
    }
    public string ToAbsoluteUrl(string relativeUrl)
    {
        if (string.IsNullOrEmpty(relativeUrl))
        {
            return relativeUrl;
        }
        if (relativeUrl.StartsWith("/"))
        {
            relativeUrl = relativeUrl.Insert(0, "~");
        }

        if (!relativeUrl.StartsWith("~/"))
        {
            relativeUrl = relativeUrl.Insert(0, "~/");
        }

        var url = HttpContext.Current.Request.Url;
        var port = url.Port != 80 ? (":" + url.Port) : String.Empty;

        return String.Format("{0}://{1}{2}{3}", url.Scheme, url.Host, port, VirtualPathUtility.ToAbsolute(relativeUrl));
    }
.NET
.NET
Microsoft Technologies based on the .NET software framework.
4,103 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,598 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,336 questions
0 comments No comments
{count} votes

Accepted answer
  1. Lan Huang-MSFT 30,176 Reputation points Microsoft External Staff
    May 1, 2023, 9:32 AM

    Hi @Donald Symmons,

    I wrote an example according to your needs, you can refer to:

    <asp:TextBox ID="txtCode" runat="server"></asp:TextBox>
            <asp:Button ID="btnGenerate" runat="server" Text="Generate" OnClick="btnGenerate_Click" />
            <hr />
            <asp:Image ID="LogoImage" runat="server" />
            <asp:Image ID="QRImage1" runat="server" Width="150" Height="150" />
    
     protected void Page_Load(object sender, EventArgs e)
            {
                Showdata1();
    
            }
            public void Showdata1()
            {
                //In this public void, the logo image is read from the database table and displayed on the web form.
                string connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
                using (SqlConnection con = new SqlConnection(connectionString))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT * FROM tblFiles WHERE Id = 1", con))
                    {
    
                        con.Open();
                        SqlDataReader dr = cmd.ExecuteReader();
                        if (dr.Read())
                        {
                            byte[] bytes = (byte[])dr["Data"];
                            LogoImage.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(bytes);
                        }
                    }
                }
            }
            protected void btnGenerate_Click(object sender, EventArgs e)
            {
                string code = txtCode.Text;
                byte[] image = Convert.FromBase64String(LogoImage.ImageUrl.Replace("data:image/jpeg;base64,", String.Empty));
                QRCodeGenerator qrGenerator = new QRCodeGenerator();
                QRCodeData qrCodeData = qrGenerator.CreateQrCode(code, QRCodeGenerator.ECCLevel.Q); QRCode qrCode = new QRCode(qrCodeData);
                using (Bitmap bitMap = qrCode.GetGraphic(40))
                {
                    Bitmap overlay = new Bitmap(new MemoryStream(image));
                    int deltaHeigth = bitMap.Height - overlay.Height;
                    int deltaWidth = bitMap.Width - overlay.Width;
                    Graphics g = Graphics.FromImage(bitMap);
                    g.DrawImage(overlay, new System.Drawing.Point(deltaWidth / 2, deltaHeigth / 2));
                    using (MemoryStream ms = new MemoryStream())
                    {
                        bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                        byte[] byteImage = ms.ToArray();
                        QRImage1.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
                    }
    
                }
            }     
    

    6

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.