简体   繁体   English

NodeJS将图像流转换为base64会提供无效数据

[英]NodeJS converting image stream to base64 gives invalid data

I'm trying to generate a QR code and then return it as a Base64-encoded data URL. 我正在尝试生成QR码,然后将其作为Base64编码的数据URL返回。 I know that there's a module ( https://github.com/cmanzana/qrcode-npm ) which is supposed to be able to do this directly, but I'm having trouble installing the canvas module dependency. 我知道有一个模块( https://github.com/cmanzana/qrcode-npm )应该可以直接执行此操作,但是我在安装canvas模块依赖项时遇到了麻烦。 I'm still working on that front but for now, my attempted workaround is to generate an image stream with an alternate module, then convert it to Base64. 我仍在这方面进行工作,但现在,我尝试的解决方法是使用备用模块生成图像流,然后将其转换为Base64。 This is what I have so far: 这是我到目前为止的内容:

var qrBase64 = '';
var qrImg = qr.image(qrText, { type: 'png', ec_level: 'L' });

qrImg.on('readable', function () {
    qrBase64 += qrImg.read().toString('base64');
});

qrImg.on('end', function () {
    qrBase64 = "data:image/png;base64," + qrBase64;
    return res.json({
        success: true,
        qrBase64: qrBase64
    });
});

It seems to work in that it gives me a string which resembles a Base64-encoded string. 它的工作方式似乎是给了我一个类似于Base64编码字符串的字符串。 However, if I try to view it in a browser, I get an invalid URL error. 但是,如果尝试在浏览器中查看它,则会收到无效的URL错误。 If I pipe the qrImg to a file and then use an online tool to convert it to Base64, the result (which is valid and works in a browser) does not match my Node result. 如果我将qrImg管道qrImg到文件,然后使用在线工具将其转换为Base64,则结果(有效且在浏览器中有效)与我的Node结果不匹配。

You need to base64 encode all of the image data at once. 您需要一次对所有图像数据进行base64编码。 Concatenating chunks before and after base64 encoding usually doesn't yield the same result. 在base64编码之前和之后串联块通常不会产生相同的结果。 Take a look at this example: 看一下这个例子:

btoa("12" + "34")         -> "MTIzNA=="

btoa("12") + btoa("34")   -> "MTI=MzQ="

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

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