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

How to convert Buffer to base64 image in 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>
  }
]
*/ 

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

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

Buffer.toString() 也可以采用其他编码,您可以在 docs.

中阅读更多关于其他支持的编码的信息

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

const dataImagePrefix = `data:image/png;base64,`
const query = 'SELECT image FROM table WHERE id=(SELECT max(id) FROM table)'

connection.query(query, (err, result, fields) => {
  if (err) {
    console.log(err)
    
    // Exit after handling error
    return 
  }

  // Return all results and for each result row
  // convert to a base64 string with the dataImagePrefix prepended to each
  return results.map(result => `${dataImagePrefix}${result.image.toString('base64')}`)
})