1

I have sent the image file in a byte array from the server. Now I have to convert that into a jpeg file and display it in a webpage.

Code:

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"});
    })    
});

I am receiving the data from the backend; now I need to convert this into an image in angular6

3
  • What have you already tried? Commented Nov 20, 2018 at 10:54
  • Does this help you maybe? stackoverflow.com/questions/48781966/… Commented Nov 20, 2018 at 10:56
  • no that answer doesnt work because i am sending the buffer data to front end Commented Nov 22, 2018 at 6:06

1 Answer 1

5

You can convert a byte array to a Base64-encoded string using the btoa function, and then use a Data URL to display the image. You will need to known the image's MIME type though:

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
Sign up to request clarification or add additional context in comments.

3 Comments

@SanjeevKumar which error exactly and where? I assume you replaced the [...] placeholder with actual code that gets the byte array from server?
@SanjeevKumar sorry, my bad - please see the updated answer
The btoa function expects an array of number, not an Uint8Array. How to solve this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.