Adding logo image from asp:Image control to a QR code image

Donald Symmons 3,066 Reputation points
2022-12-26T12:55:34.267+00:00

I have this C# that generates QR code image, but I want to be able to place a logo in the middle of the QR image. The logo image will be gotten from an image asp:Image control. I search for solutions online but I could only find that they all get their logo from a path (maybe a folder or from fileupload control). But my logo is displayed in an asp image control from database. So I was thinking that if I could get it directly from asp image control and place in the QR code generator it will be great.

From the tutorials I am seeing online, their logo image is uploaded from a file upload control. But my logo image is displayed in the asp Image control.
This is how I see it online.

public byte[] GetQRCodeByte(string url)  
   {  
       string path = "c:\\code\\projects\\CodeCreator\\CodeCreator\\";  
       QRCodeEncoder encoder = new QRCodeEncoder();  
   
       encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H; //30%  
       encoder.QRCodeScale = 10;  
   
       Bitmap bmp = encoder.Encode(TextBox1.Text);  
       LogoUpload.SaveAs(path + LogoUpload.FileName);  
   
       System.Drawing.Image logo = System.Drawing.Image.FromFile(path + LogoUpload.FileName);  
   
       int left = (bmp.Width / 2) - (logo.Width / 2);  
       int top = (bmp.Width / 2) - (logo.Width / 2);  
   
       Graphics g = Graphics.FromImage(bmp);  
   
       g.DrawImage(logo, new Point(left, top));  
   
       bmp.Save(path + "img.jpg", ImageFormat.Jpeg);  
   
       Image3.ImageUrl = "img.jpg";  
   }  

But I am not using a fileupload control to upload my logo. my logo is displayed from the database table in the asp:Image control (Image1) . I want to add the logo image to the middle of the QR code.

I have a QR code encoder that creates a QR code

public byte[] GetQRCodeBytes(string url)  
{  
    QRCodeEncoder encoder = new QRCodeEncoder();  
    Bitmap bi = encoder.Encode(url);  
    MemoryStream tmpSteam = new MemoryStream();  
    bi.Save(tmpSteam, ImageFormat.Jpeg);  
    return tmpSteam.ToArray();  
}  

This code displays my logo image from database

protected void Page_Load(object sender, EventArgs e)  
{  
    showdata1();  
}  
public void showdata1()  
{  
     SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security = True");  
 con.Open();  
 SqlCommand cmd = new SqlCommand();  
 cmd.CommandText = "SELECT * FROM Users WHERE email = '" + Label2.Text + "'";  
 cmd.Connection = con;  
 SqlDataAdapter sda = new SqlDataAdapter();  
 DataSet ds = new DataSet();  
 sda.SelectCommand = cmd;  
 sda.Fill(ds, "detail");  
 if (ds.Tables[0].Rows.Count > 0)  
 {  
 Label2.Text = ds.Tables[0].Rows[0]["email"].ToString();  
 byte[] image = (byte[])ds.Tables[0].Rows[0]["Logo"];  
 Image1.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(image);  
 }  
}  

Then when I click on button to create QR code, the QR code will display with the logo image in the center.

protected void Button3_Click(object sender, EventArgs e)  
{  
    // Bind Image3 for QR code  
    byte[] QRBytes = GetQRCodeBytes(ToAbsoluteUrl("/myqrwebpage.aspx"));  
    Image3.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));  
   }  

I am using MessagingToolKit

namespace

using MessagingToolkit.QRCode.Codec.Data;  
using MessagingToolkit.QRCode.Codec;  

Here is my HTML

<div class="col-sm-12">  
            <asp:Label ID="Label2" runat="server" Text="******@gmail.com"></asp:Label>  
            <div class="pict" style="float: left; margin-left: 5%; margin-bottom: 3%;">  
                <asp:Image ID="Image1" runat="server" Width="80px" Height="80px" />  
            </div>  
        </div>  
        <br />  
        <div class="col-sm-12">  
            <div class="pict" style="float: left; margin-left: 5%; margin-bottom: 3%;">  
                <asp:Image ID="Image3" runat="server" Width="80px" Height="80px" />  
            </div>  
        </div>  
        <br />  
        <div class="col-sm-12">  
            <asp:Button ID="Button3" runat="server" Text="QR Code" OnClick="Button3_Click" />  
        </div>  
Developer technologies ASP.NET Other
Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. QiYou-MSFT 4,326 Reputation points Microsoft External Staff
    2022-12-28T09:01:12.447+00:00

    Hi @Donald Symmons ,
    In fact, I think you don't think the problem is so complicated, since you have a way to upload local files to achieve the function, then we can save the image files in the database to the local first.

    string DownLoadFileName;   
    public  void DownLoadPicture()    
            {  
                if (DownLoadFileName == "")  
                {  
                    MessageBox.Show("Enter a file name");  
                    return;  
                }  
                SqlConnection conn = GetConn();  
                string sqlstr = string.Format("your sql command");  
                SqlCommand comm = new SqlCommand(sqlstr, conn);  
                    comm.Parameters.AddWithValue("@fileName", this.DownLoadFileName);  
          
                    SqlDataReader datereader = comm.ExecuteReader();  
          
                    if (datereader.HasRows)  
                    {  
                        if (datereader.Read())  
                        {  
                            this.picture = (byte []) dr["Picture"];  
                              
                            FileStream fs = new FileStream(DownLoadFileName, FileMode.Create, FileAccess.Write);  
                            fs.Write(picture, 0, picture.Length);  
                            fs.Close();  
          
                            dr.Close();  
                            conn.Close();                          
                        }  
          
                    }//if  
                    else  
                    {  
                        MessageBox.Show("None");  
                        return;  
                    }  
          
                }  
              
            }  
        }  
    

    Best Regards,
    Qi You


    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.


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.