如何在cordova中将图像从库转换为base64

时间:2016-06-22 11:41:05

标签: cordova base64

我想将图片转换为Base64。

使用案例:用户从图库中选择图像,我想将其发送到服务器以base64格式上传。我使用了cordova相机,它成功地从画廊中选择了图像。但问题是 - 无法将其转换为base64。

我已使用navigator.camera.getPicture,成功后我获得content://media/external/images/media/18604,我已尝试将其转换为:



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);
             };
             img.src = imageData;
             var dataURL = c.toDataURL("image/jpeg");




Js代码:



document.addEventListener("deviceready", function() {
          navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
            destinationType: Camera.DestinationType.FILE_URI,
            sourceType: Camera.PictureSourceType.PHOTOLIBRARY });

          function onPhotoURISuccess(imageData) {
            console.log("onPhotoURISuccess..")
           //var image = document.getElementById('myImage');
           var image = imageData;
          //this is printing - content://media/external/images/media/18604
		   console.log("Image..." + image);

        }

        function onFail(e){
            console.log("onFail..Err.." + e);
        }
}, false);




它似乎不起作用,如果我拿一个本地jpeg,它可以工作!

1 个答案:

答案 0 :(得分:3)

您是否尝试过Camera.destinationType.DATA_URL

documentation清楚地解释了如何调用camera.getPicture以获得base64输出(此代码来自文档):

navigator.camera.getPicture(onSuccess, onFail, { quality: 25,
    destinationType: Camera.DestinationType.DATA_URL
});

function onSuccess(imageData) {
    var image = document.getElementById('myImage');
    image.src = "data:image/jpeg;base64," + imageData;
}

function onFail(message) {
    alert('Failed because: ' + message);
}

注意:请注意,base64操作内存非常密集,可能会冻结应用程序,尤其是在预算手机中。