gpt4 book ai didi

javascript - 如何从 API 读取图像数据并在 React Component 中渲染

转载 作者:行者123 更新时间:2023-12-04 15:44:23 25 4
gpt4 key购买 nike

我正在尝试从 Web 服务呈现图像数据并能够获取如下数据

enter image description here

我正在尝试读取的图像数据如下所示,但图像未显示,

getImageFromDrive = (path) => {
let that = this;
axios.get(Constants.API + Constants.Files, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
"Authorization": Constants.AUTH_Element + ',' + Constants.AUTH_ORG + ',' + Constants.AUTH_USER
},
params: {
path: path
}
}).then(function (response) {
var myThat =that;
console.log(response);
let data = response.data;
var base64Flag = 'data:image/jpeg;base64,';
var imageStr =
that.arrayBufferToBase64(data.img.data.data);
that.setState({img: base64Flag + imageStr});

})
.catch(function (error) {
console.log(error);
})
}
arrayBufferToBase64(buffer) {
var binary = '';
var bytes = [].slice.call(new Uint8Array(buffer));
bytes.forEach((b) => binary += String.fromCharCode(b));
return window.btoa(binary);
};

render() {
const {img} = this.state;

return (

<img className="myImg" alt="" width="300"
height="300" src={img}/>
)
}

谁能建议我如何读取那种数据并显示

最佳答案

试试下面的代码。

export async function getImageData() {
await axios.get(`your api url`, {responseType: 'arraybuffer'}).then((data) => {
const b64Data = btoa(
new Uint8Array(data.data).reduce(
(dataArray, byte) => {
return dataArray + String.fromCharCode(byte);
},
''
)
);
const userAvatarData = {
key: 'userAvatar',
value: `data:image/png;base64,${b64Data}`
};
return userAvatarData.value; // here we return the base64 image data to our component
});
}

关于javascript - 如何从 API 读取图像数据并在 React Component 中渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56504851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com