Dan
Dan

Reputation: 2344

Converting Image Hex to base64 in JavaScript

I'm looking for a way to convert a hex image (for example a jpg in hex form) back to base64 in order to display the image in a web page.

I have been using the code below for smaller images but it fails for larger images with a max call stack exceeded error.

src below is the source of the image in hex format.

test.img = new Image();
test.img.src = "data:image/jpg; base64," + hexToBase64(src);

function hexToBase64(str) {
    return btoa(String.fromCharCode.apply(null, str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
}

Upvotes: 2

Views: 2865

Answers (1)

traktor
traktor

Reputation: 19301

The max call stack exceeded error is being generated by converting the hex string into an array and supplying it to String.fromCharCode() as an arguments array using the apply method from Function.prototype.

There are practical limits on how many arguments can be passed in JavaScript function calls so the method can work for small files and fail for larger ones.

Refactoring the code will be necessary. As an untested basic solution

function hexToBase64(str) {
    var bString = "";
    for( var i = 0; i < str.length; i +=2) {
         bString += String.fromCharCode( parseInt( str.substr( i, 2), 16));
    }
    return btoa(bString);
}

may provide some ideas.

Upvotes: 4

Related Questions