【问题标题】:How to convert Buffer to base64 image in Node js如何在Node js中将Buffer转换为base64图像
【发布时间】:2022-02-03 05:22:39
【问题描述】:

我正在从我的 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>
  }
]
*/ 

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

【问题讨论】:

    标签: mysql sql node.js image base64


    【解决方案1】:

    由于您接收的是 Buffer 作为输出,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')}`)
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-12
      • 1970-01-01
      • 2014-11-03
      • 1970-01-01
      • 2022-12-25
      • 2020-03-24
      • 2013-11-07
      • 1970-01-01
      相关资源
      最近更新 更多