Javascript 从文件路径检索图像并将其编码为Base64
我需要从提供的映像文件路径转换Base64。以下是转换代码:Javascript 从文件路径检索图像并将其编码为Base64,javascript,cordova,Javascript,Cordova,我需要从提供的映像文件路径转换Base64。以下是转换代码: var encodeImageUri = function(imageUri, callback) { var c = document.createElement('canvas'); var ctx = c.getContext("2d"); var img = new Image(); img.onload = function() { c.width = this.width;
var encodeImageUri = function(imageUri, callback) {
var c = document.createElement('canvas');
var ctx = c.getContext("2d");
var img = new Image();
img.onload = function() {
c.width = this.width;
c.height = this.height;
ctx.drawImage(img, 0, 0);
if(typeof callback === 'function'){
var dataURL = c.toDataURL("image/jpeg");
callback(dataURL);
}
};
img.src = imageUri;
}
function getFileContentAsBase64(path,callback){
console.log(path);
window.resolveLocalFileSystemURL(path, gotFile, fail);
function fail(e) {
alert(JSON.stringify(e));
}
function gotFile(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
var content = this.result;
callback(content);
};
// The most important point, use the readAsDatURL Method from the file plugin
reader.readAsDataURL(file);
});
}
}
我如何使用它:
var image = 'file://' + path;
getFileContentAsBase64(image, function (base64File) {});
encodeImageUri(image, function(base64){});
路径
示例:
file:///storage/emulated/0/test.jpeg
如果我将base64结果打印到,则其中一个已损坏,大小仅为3kb,另一个是错误,图像图标已损坏。您的帖子中哪里是您正在检索的示例base64字符串?您的帖子中哪里是您正在检索的示例base64字符串?