首页 > 解决方案 > 在 React 的 ArrayBuffer 中显示 PNG 图像

问题描述

在进行 JavaScript 调用后,我试图让图像(PNG 格式)显示在 React 应用程序中。代码如下。函数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 函数中的任何错误?

标签: javascriptreactjsarraybuffer

解决方案


制作这个 ArrayBuffer 的 Blob 并通过 blob-URI 使您的图像指向这个 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


推荐阅读