How convert type data buffer to image in react js

怎甘沉沦 提交于 2021-01-07 01:41:53

问题


Hello, i have next the image de type buffer, this data is one image, how can I convert my buffer data into an image

it shows me the following data when I make the request to the api

Any suggestion

The backend is made in node js sequelize MYSQL.

and the frontend in react js

I have next example

https://codesandbox.io/s/happy-christian-z4m1x?file=/src/LoadingData.js

With this he retrieved the data from the MySQL database

In this way I register

and in this way the image is stored


回答1:


First, you need to convert your Buffer to base64 string

const base64String = btoa(String.fromCharCode(...new Uint8Array(arrayBuffer)));

Second, you need to use your string as src attribute for img tag

<img src={`data:image/png;base64,${base64String}`} alt=""/>

I assume you are using react, so I recommend saving base64String in the component state and using it.




回答2:


Hello I managed to solve this problem with this function I hope it helps you

// here I extract the data from arrayBuffer
const  { data } = pregunta;
console.log( data );

here we convert the data into base64

const img = new Buffer.from(data).toString("ascii")
console.log(img);

And result is

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/ ..... continue

Thanks



来源:https://stackoverflow.com/questions/65392241/how-convert-type-data-buffer-to-image-in-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!