NodeJS base64 图像响应不是作为图像对象出现的。添加标题 {'内容类型': '图像/jpeg 或 png'} 时



当我在服务器端生成图像并获取base64图像字符串时。

我想作为图像对象发送。它通过创建图像流与节点画布正常工作。

    let stream = this.canvas.jpegStream({progressive: true});
    this.res.writeHead(200, {
        'Content-Type': 'image/jpeg'
    });
    stream.on('data', (chunk) => {
        this.res.write(chunk);
    });
    stream.on('end', () => {
        this.res.end(); 
    });
// Working perfectly...!

但是当我使用织物时.js它返回的是直接的base64图像,而不是像node-canvas那样的base64流。 当我发送 base64 作为响应时,图像是空白的。

    this.res.writeHead(200, {
        'Content-Type': 'image/png'
    });
    this.res.write(this.fabricCanvas.toDataURL());
    this.res.end();

Content-Type: image/png不是用于data: URL的正确标头。

您可以尝试以下方法之一:

// Preferred: returns a PNG-encoded image buffer
this.fabricCanvas.toBuffer()
// Wasteful - goes from binary to base64 and back
Buffer.from(this.fabricCanvas.toDataURL().split(",")[1], "base64")

最新更新