在 React 中的 ArrayBuffer 中显示 PNG 图像

IT技术 javascript reactjs arraybuffer
2021-04-29 02:20:35

我正在尝试在进行 JavaScript 调用后获取要在 React 应用程序中显示的图像(PNG 格式)。代码如下。函数DeviceService.getFile以 blob 形式返回文件。数据是二进制的。如何在 React 中正确显示此图像?

我已经尝试转换为 base64,但没有帮助。

DeviceService.getFile(mapOverlayImagePath, bMap1 => {
        this.setState({ MapOverlay: bMap1 })
        // this.setState({ MapOverlay: 'data:image/png;base64,' + btoa(bMap1) })
        console.log(bMap1)
      })

显示图像的 React 代码:

<img src={this.state.MapOverlay} alt="MapOverlay" />

我修改了这个函数,函数getFile如下:

export function getFile(path, cb) {
  if (typeof(cb) === 'undefined' || cb === null)
    return;

  fetch(uris.getFile() + '/?' +
    'path=' + path,
    {method: 'POST', credentials: 'include'})
    .then(reply => reply.blob())
    .then((response) => {
      if (response.data) {
        return cb(response.data);
      }
      return cb(new Blob());
    })
}

这个 getFile 函数位于一个库中,它在 React 应用程序中用作依赖项。

我尝试在 Internet Explorer 控制台中打印 blob 大小并显示:[object Blob]: {size: 0, type: ""}. 我想我的 getFile 函数没有按预期传递数据。getFile 函数中的任何错误?

1个回答

使用 blob-URI 制作此 ArrayBuffer 的 Blob,并使您的图像指向此 Blob。

fetch( 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png' )
  .then( r => r.arrayBuffer() )
  .then( buffer => { // note this is already an ArrayBuffer
    // there is no buffer.data here
    const blob = new Blob( [ buffer ] );
    const url = URL.createObjectURL( blob );
    const img = document.getElementById( 'img' );
    img.src = url;
    // So the Blob can be Garbage Collected
    img.onload = e => URL.revokeObjectURL( url );
    // ... do something else with 'buffer'
  } );
<img id="img">

但如果你真的不需要 ArrayBuffer,那么让浏览器直接将 Response 作为 Blob 消费:

fetch( 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png' )
  .then( r => r.blob() ) // consume as a Blob
  .then( blob => { 
    const url = URL.createObjectURL( blob );
    const img = document.getElementById( 'img' );
    img.src = url;
    // in case you don't need the blob anymore
    img.onload = e => URL.revokeObjectURL( url );
  } );
<img id="img">

但是,在您的位置上,我什至会尝试直接从您的<img>to发出一个简单的 GET 请求uris.getFile() + '/?path=' + path