将字节数组转换为 angular6 中的图像

San*_*mar 1 typescript ipfs angular

我已经从服务器以字节数组的形式发送了图像文件。现在我必须将其转换为jpeg文件并将其显示在网页中。

代码:

app.get('/getPhoto/:hash',function(req, res){
    console.log(req.params.hash);
    invoke = require('/Users/sanjeev.natarajan/ipfs/file1.js');

    invoke.getfile(req.params.hash).then((str)=>{
        console.log("resu",str)

        res.send({"Result":str});
    })
    .catch((error) => {
        res.send({"Error":"error in fetching the file through the hashcode"});
    })    
});
Run Code Online (Sandbox Code Playgroud)

我正在从后端接收数据;现在我需要将其转换为 angular6 中的图像

Imp*_*rks 5

您可以使用btoa函数将字节数组转换为 Base64 编码的字符串,然后使用数据 URL来显示图像。不过,您需要知道图像的 MIME 类型:

var bytes = [ ... ]; // get from server
var uints = new UInt8Array(bytes);
var base64 = btoa(String.fromCharCode(null, uints));
var url = 'data:image/jpeg;base64,' + base64; // use this in <img src="..."> binding
Run Code Online (Sandbox Code Playgroud)

  • btoa 函数需要一个数字数组,而不是 Uint8Array。怎么解决这个问题呢? (2认同)