Как конвертировать изображение с устройства в base64 с помощью JavaScript в Cordova

Чтобы преобразовать файл в base64 (изображение или любой другой вид файла) с помощью cordova, ionic или phonegap, нам понадобится только плагин файла cordova и 1 человеческий глаз. Затем мы будем использовать FileReader для чтения содержимого файла с помощью метода readAsDataURL.

/**
* This function will handle the conversion from a file to base64 format
*
* @path string
* @callback function receives as first parameter the content of the image
*/
function getFileContentAsBase64(path,callback){
window.resolveLocalFileSystemURL(path, gotFile, fail);
function fail(e) {
alert('Cannot found requested file');
}
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);
});
}
}

Затем мы будем использовать его для преобразования локального изображения в base64:

var path = "file://storage/0/downloads/myimage.png";
// Convert image
getFileContentAsBase64(path,function(base64Image){
//window.open(base64Image);
console.log(base64Image);
// Then you'll be able to handle the myimage.png file as base64
});

Помните, что вам нужен файл плагина от Cordova, прочитайте и узнайте, как использовать это здесь. Вы можете загрузить плагин файла в свой проект, выполнив его в CLI Cordova:

cordova plugin add cordova-plugin-file
Ссылка на основную публикацию
Adblock
detector