个性化阅读
专注于IT技术分析

如何在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)
未经允许不得转载:srcmini » 如何在Cordova中使用javascript将图像从设备转换为base64

评论 抢沙发

评论前必须登录!