Skip to content
Advertisement

How to convert Buffer to base64 image in Node js

I am getting data from my SQL database like this:

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>
  }
]
*/ 

How can I convert result to a base64 image in Node.js? For Example: 'data:image/png;base64,iVBORw0KGgoAAAANS'

Advertisement

Answer

Since you’re receiving a Buffer back as output, Buffer.toString('base64') will convert the raw binary data in the buffer to a base64 representation of the data.

Buffer.toString() can also take other encodings, you can read more about the other supported encodings in the docs.

So for your above code you would use this to get your image as 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')}`)
})
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement