简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM