android base64 javascript,如何在Cordova中使用javascript将图像从设备转换为base64

要将具有cordova, ionic或phonegap的文件转换为base64(图像或任何其他类型的文件), 我们将只需要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的文件插件, 请在此处阅读和学习如何使用它。你可以将文件插件下载到在你的cordova CLI中执行的项目中:

cordova plugin add cordova-plugin-file

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值