首页 > 解决方案 > 如何在 React 中将 ArrayBuffer(PNG 图像)直接渲染为图像?

问题描述

我得到一个表示通过套接字发送的 PNG 图像文件的 ArrayBuffer。有没有一种方法可以直接将其渲染到图像选项卡,而无需先将其转换为 base64?似乎没有必要仅为渲染添加额外的转换步骤。

标签: javascriptreactjsbase64pngarraybuffer

解决方案


您可以将数组缓冲区转换为 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>


推荐阅读