javascript - 如何在 React 中将 ArrayBuffer(PNG 图像)直接渲染为图像?
问题描述
我得到一个表示通过套接字发送的 PNG 图像文件的 ArrayBuffer。有没有一种方法可以直接将其渲染到图像选项卡,而无需先将其转换为 base64?似乎没有必要仅为渲染添加额外的转换步骤。
解决方案
您可以将数组缓冲区转换为 blob,然后用于URL.createObjectURL(blob)
创建图像的源。
例子
const { useState, useEffect } = React;
const url = "https://cors-anywhere.herokuapp.com/https://www.w3schools.com/howto/img_avatar2.png"
const App = () => {
const [{
srcBlob,
srcDataUri
}, setSrc] = useState({
srcBlob: null,
srcDataUri: null
});
useEffect(() => {
let isUnmounted = false;
fetch(url, {
})
.then(response => response.blob())
.then(blob => blob.arrayBuffer())
.then(arrayBuffer => {
if(isUnmounted) {
return;
}
const blob = new Blob([arrayBuffer])
const srcBlob = URL.createObjectURL(blob);
setSrc(state => ({
...state,
srcBlob
}));
})
return () => {
isUnmounted = true;
}
}, [])
return <div>
{srcBlob && <div>
<img width="100" height="100" src={srcBlob} alt="image blob"/>
<div>Blob: {srcBlob}</div>
</div>}
</div>
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>
推荐阅读
- sql - 如何使用 SQL xmlserialize 函数添加 XML CDATA 部分?
- pysnmp - 如何使用 pysnmp 将自定义消息与 mib 一起传递
- javascript - 当使用 AJAX 从烧瓶返回值时,它显示 [Object, Object]
- c - 如何结合两个功能?
- tcp - 如果仍有未确认的数据包,TCP 连接是否被视为空闲?
- c# - 如何将字符串转换为类对象?C# WinForms
- heatmap - 具有某些单元格的自定义多色的 HeatMap
- r - 在 R 中解析日期
- bash - 什么是无效的间接扩展,为什么它会阻止我安装这个程序?
- asp.net-mvc - MVC 表单加载中的图像但在 Chrome 中不可见