Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I call a code image to use in HTML?

I’m using this code to create a QR code (C#):

string text = "QRCode test";
            QRCodeGenerator qr = new QRCodeGenerator();
            QRCodeData data = qr.CreateQrCode(text, QRCodeGenerator.ECCLevel.Q);
            QRCode code = new QRCode(data);
            
            Image img = code.GetGraphic(5);

Then I’m trying to insert it into an HTML like this (HTML):

<img src='{img}'>

I don’t know how to do for the image to get to the code because from what I know the "src" only goes to the device or the internet.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could save the image to a file, such as a PNG file, and then use the file’s path as the src attribute of the img element:

string text = "QRCode test";
QRCodeGenerator qr = new QRCodeGenerator();
QRCodeData data = qr.CreateQrCode(text, QRCodeGenerator.ECCLevel.Q);
QRCode code = new QRCode(data);

Image img = code.GetGraphic(5);

img.Save("qrcode.png", System.Drawing.Imaging.ImageFormat.Png);

string html = $"<img src='qrcode.png' alt='QR code'>";

Alternatively, you can use a data URI to embed the image directly into the img element without saving it to a file. To do this, you can convert the image to a base64-encoded string and use it as the src attribute of the img element:

string text = "QRCode test";
QRCodeGenerator qr = new QRCodeGenerator();
QRCodeData data = qr.CreateQrCode(text, QRCodeGenerator.ECCLevel.Q);
QRCode code = new QRCode(data);

Image img = code.GetGraphic(5);


using (MemoryStream ms = new MemoryStream())
{
    img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    byte[] imageBytes = ms.ToArray();
    string base64 = Convert.ToBase64String(imageBytes);
    string imgSrc = "data:image/png;base64," + base64;

    string html = $"<img src='{imgSrc}' alt='QR code'>";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading