Reputation: 6134
I want to convert an image into Base64.
Use case: User chooses image from gallery and I want to send it to server to upload in base64 format. I used cordova camera and it successfully chose image from gallery. But problem is - unable to convert it to base64.
I've used navigator.camera.getPicture
, and on success I get content://media/external/images/media/18604
, which I've tried to convert to:
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 code:
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);
It doesn't seem to work, if I take a local jpeg, it works!
Upvotes: 2
Views: 4262
Reputation: 16294
Have you tried with Camera.destinationType.DATA_URL
?
The documentation clearly explains how to call the camera.getPicture
in order to have a base64 output (this code is from docs):
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);
}
Note: please be aware that base64 operations are very memory intensive and could freeze the app especially in budget phones.
Upvotes: 3