简体   繁体   English

在JavaScript中将Image Hex转换为base64

[英]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. 我正在寻找一种将十六进制图像(例如,十六进制形式的jpg)转换回base64的方法,以便在网页中显示该图像。

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. 下面的src是十六进制格式的图像源。

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 . 使用Function.prototypeapply方法,通过将十六进制字符串转换为数组并将其作为参数数组提供给String.fromCharCode()来生成最大调用堆栈超出错误。

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. 在JavaScript函数调用中可以传递多少个参数有实际的限制,因此该方法适用于较小的文件,不适用于较大的文件。

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. 可能提供一些想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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