【问题标题】:How can I render an ArrayBuffer (PNG image) directly as an image in React?如何在 React 中将 ArrayBuffer(PNG 图像)直接渲染为图像?
【发布时间】:2020-10-05 01:08:55
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs base64 png arraybuffer


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-30
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多