jaimefps
jaimefps

Reputation: 2414

How to display buffered image

I'm creating a "load picture" component in ReactJS. My component stores a loaded image in memory and sends it to a Node server that is using npm "file-loader".

The image reaches the server as a buffer <Buffer 89 12 00 .... >

I will try to save the buffer to a MySQL, but then need to display the image as a thumbnail in the browser if the DB insert was successful.

How do I display a buffered image in the broswer?

Upvotes: 2

Views: 6825

Answers (1)

jaimefps
jaimefps

Reputation: 2414

The solution I went with was to transform the buffer to base64 and display it with an <img /> tag:

const buffer = someData // e.g., <Buffer 89 50 4e ... >
const b64 = new Buffer(buffer).toString('base64')
const mimeType = some_type // e.g., image/png

Then in my React component I render an image tag as such:

<img src={`data:${mimeType};base64,${b64}`} />

More here: https://css-tricks.com/data-uris/

Upvotes: 6

Related Questions