[英]Base64 - Invalid Encoding
I try to convert my image binary to base64 using this code but still not successful. 我尝试使用此代码将图像二进制文件转换为base64,但仍未成功。
I got invalid base64 string. 我收到无效的base64字符串。 Verify using this tool.
使用此工具进行验证。
http://www.freeformatter.com/base64-encoder.html http://www.freeformatter.com/base64-encoder.html
var img = document.getElementById('image');
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
These solutions not helping me at all. 这些解决方案根本没有帮助我。 I hope can get the answer soon.
我希望能尽快得到答案。
Result +mdHoAAAAASUVORK5CYII= 结果+ mdHoAAAAASUVORK5CYII =
Thanks. 谢谢。
I got the answer. 我得到了答案。
var img = document.getElementById('image');
var oReq = new XMLHttpRequest();
oReq.open("GET", img, true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
var arrayBuffer = oReq.response; // Note: not oReq.responseText
if (arrayBuffer) {
var x = img.split('.');
var ext = x[x.length - 1];
var b64img = _arrayBufferToBase64(arrayBuffer);
$('<img />').attr('src', 'data:image/' + ext + ';base64,' + b64img).appendTo($('body'));
}
};
oReq.send(null);
function _arrayBufferToBase64(buffer) {
var binary = ''
var bytes = new Uint8Array(buffer)
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i])
}
return window.btoa(binary);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.