如何在Node js中将Buffer转换为base64图像

Srk*_*rki 7 mysql sql base64 image node.js

我从 SQL 数据库获取数据,如下所示:

const mysql = require("mysql");

const connection = mysql.createConnection({
    host: "localhost",
    user: "root",
    database: "database",
    password : ''
  });
  //connection.release();
  connection.connect(function(err) {
    if (err) console.log(err);
  });

  connection.query("SELECT image FROM table WHERE id=(SELECT max(id) FROM table);", function (err, result, fields) {
    if (err) console.log(err);
    console.log(result);
  });

/*Output:
[
  RowDataPacket {
    image: <Buffer 64 61 74 61 3a 69 6d 61 67 65 2f 6f 63 74 65 74 2d 73 74 72 65 61 6d 3b 62 61 73 65 36 34 2c 69 56 42 4f 52 77 30 4b 47 67 6f 41 41 41 41 4e 53 55 68 ... 27941 more bytes>
  }
]
*/ 
Run Code Online (Sandbox Code Playgroud)

如何result在 Node.js 中转换为 Base64 图像?例如: 'data:image/png;base64,iVBORw0KGgoAAAANS'

pet*_*teb 7

由于您\xe2\x80\x99 接收到一个缓冲区作为输出,因此Buffer.toString(\'base64\')会将缓冲区中的原始二进制数据转换为数据的 Base64 表示形式。

\n

Buffer.toString()还可以采用其他编码,您可以在文档中阅读有关其他支持的编码的更多信息。

\n

因此,对于上面的代码,您可以使用它来将图像获取为 base64

\n
const dataImagePrefix = `data:image/png;base64,`\nconst query = \'SELECT image FROM table WHERE id=(SELECT max(id) FROM table)\'\n\nconnection.query(query, (err, result, fields) => {\n  if (err) {\n    console.log(err)\n    \n    // Exit after handling error\n    return \n  }\n\n  // Return all results and for each result row\n  // convert to a base64 string with the dataImagePrefix prepended to each\n  return results.map(result => `${dataImagePrefix}${result.image.toString(\'base64\')}`)\n})\n
Run Code Online (Sandbox Code Playgroud)\n