我正在尝试在JavaScript调用后获取要在React应用中显示的图像(PNG格式)。代码如下。函数DeviceService.getFile返回ArrayBuffer中的文件。数据是二进制的。如何使该图像在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.arrayBuffer())
.then((response) => {
if (response.data) {
return cb(response.data);
}
return cb(new ArrayBuffer());
})
}
通过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>
到uris.getFile() + '/?path=' + path
发出一个简单的GET请求。