How to display a Buffer image from Node.js backend in React frontend?

Hey folks! I’m stuck trying to show an image in my React app. The image comes from my Node.js server as a Buffer object. When I log the Photo object in the console, it looks like this:

{
  type: 'Buffer',
  data: [137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, ...]
}

But when I try to use it in my React component like this:

<StyledImage src={Photo} />

Nothing shows up! Just a blank space where the image should be. Any ideas on how to make this work? I’m guessing I need to convert the Buffer somehow, but I’m not sure how. Thanks for any help!

hey there! i’ve dealt with this before. you gotta convert the buffer to a base64 string first. try something like this:

const base64 = btoa(String.fromCharCode.apply(null, Photo.data));
<StyledImage src={data:image/png;base64,${base64}} />

that should do the trick! lemme know if u need more help :slight_smile:

ooh, interesting problem! have you tried using the FileReader API? it can handle buffers nicely. something like this might work:

const reader = new FileReader()
reader.onload = (e) => setImgSrc(e.target.result)
reader.readAsDataURL(new Blob([Photo.data]))

what do u think? curious to hear if that helps!

To display a Buffer image from your Node.js backend in React, you’ll need to convert it to a format the browser can understand. One approach is to encode the Buffer as a base64 string on the server and send it to the client. Then, in your React component, you can use it like this:

<StyledImage src={`data:image/png;base64,${bufferString}`} />

Alternatively, you could create a Blob from the Buffer data on the client side and use URL.createObjectURL to generate a URL for the image. This method might be more efficient for larger images:

const blob = new Blob([new Uint8Array(photo.data)], { type: 'image/png' });
const imageUrl = URL.createObjectURL(blob);
<StyledImage src={imageUrl} />

Remember to clean up the URL object when the component unmounts to prevent memory leaks.