简体   繁体   English

创建二维码 Base64 并放入 HTML 的 IMG 标签

[英]Create QR Code Base64 and put in IMG tag of HTML

I get some JSON data and create a QR Code from it.我获取一些 JSON 数据并从中创建一个二维码。 I then want to convert that to a Base64 string and put it in an img tag in my html.然后我想将其转换为 Base64 字符串并将其放入我的 html 中的 img 标记中。 However, the QR Code doesn't image is not created.但是,不会创建 QR 码不图像。 This is how I try it:这是我尝试的方式:

// my string created from the JSON
string strInventoryData = string.Format(dataPortable, GeneratorID, MarketUnit);

// generate the QR Code
ZXing.Common.BitMatrix byteIMGNew = writer.encode(strInventoryData, 
                                           ZXing.BarcodeFormat.QR_CODE, 240, 240, null);
Bitmap bmp1 = new Bitmap(byteIMGNew.Width, byteIMGNew.Height);
Graphics g1 = Graphics.FromImage(bmp1);
 g1.Clear(Color.White);
 for (int x = 0; x < byteIMGNew.Height; ++x)
 {
    for (int y = 0; y < byteIMGNew.Width; ++y)
    {
        if (byteIMGNew[x, y])
           g1.FillRectangle(Brushes.Black, x, y, 1, 1);
        else
           g1.FillRectangle(Brushes.White, x, y, 1, 1);
    }
}

// create the base64 encoded image
System.IO.MemoryStream ms = new System.IO.MemoryStream();
bmp1.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] byteImage = ms.ToArray();
var SigBase64 = Convert.ToBase64String(byteImage);

// put it in the htm
strInnerData += "<td align='center' style='width:240px;height:240px'>
    <img alt='Embedded Image' src='data:image/png;base64,'" + SigBase64.ToString() + "' /></td>";

What am I doing wrong?我究竟做错了什么?

this code works for me:这段代码对我有用:

QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(message, BarcodeFormat.QR_CODE, 500, 500);    
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix,"png", outputStream);

String base64 = new String(Base64.getEncoder().encode(outputStream.toByteArray()));
...    
String strInnerData = "<td align='center' style='width:240px;height:240px'>"+
        "<img alt='Embedded Image' src='data:image/png;base64,'" + base64 + "' /></td>";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM