javascripthtmlangularimage-rendering

Angular2 - Maximum Call Stack Exceeded error when rendering images


In my Angular2 application, I want to show an image which is in Uint8Array format. But I am getting 'Maximum Call Stack Exceeded'. I could render images of size ~48Kb with no error. But when the image size is above ~300Kb is when I am getting this error. This is how I am rendering the image:

(<HTMLInputElement>document.getElementById("imagePreview")).src = "data:image/" + type + ";base64," +
                        btoa(String.fromCharCode.apply(null, objData.Body));

Can someone please tell me whether I am doing it in the right way. If not, please tell me how to do it correctly


Solution

  • String.fromCharcode() will run into a maximum call stack exceeded with large string data.

    To be able to convert said object to base64 you need to implement a loop based on the string length. Something like this comes to mind:

    let img: HTMLInputElement = (<HTMLInputElement>document.getElementById("imagePreview"));
    let bin : string = '';
    
    for (let i = 0, l = objData.Body.length; i < l; i++) {
        bin += String.fromCharCode(objData.Body[i]);
    }
    
    img.src = "data:image/" + type + ";base64," + btoa(bin);
    

    Perhaps it is more efficient to chunk up the string in bigger pieces than 1 character, but that's up to you to find the most speedy way :)