在React中的ArrayBuffer中显示PNG图像

use*_*639 5 javascript arraybuffer reactjs

我正在尝试在进行 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)
      })
Run Code Online (Sandbox Code Playgroud)

显示图像的 React 代码:

<img src={this.state.MapOverlay} alt="MapOverlay" />
Run Code Online (Sandbox Code Playgroud)

我修改了这个函数,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());
    })
}
Run Code Online (Sandbox Code Playgroud)

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

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

Kai*_*ido 10

将此 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'
  } );
Run Code Online (Sandbox Code Playgroud)
<img id="img">
Run Code Online (Sandbox Code Playgroud)

但如果你并不真正需要 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 );
  } );
Run Code Online (Sandbox Code Playgroud)
<img id="img">
Run Code Online (Sandbox Code Playgroud)

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