Home > Software design >  How do I call a code image to use in HTML?
How do I call a code image to use in HTML?

Time:12-24

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.

CodePudding user response:

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'>";
}
  • Related