我需要从提供的图像文件路径转换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;
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){});
path
示例:
file:///storage/emulated/0/test.jpeg
如果我将base64结果打印到Code Beautifier,则其中一个仅损坏了3kb大小,而另外1个则损坏了图像图标。