Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PhoneGap, How to get base64 image data of the photo chosen from photo library in iPhone

Using PhoneGap(Cordova), Am trying to get base64 image data of the photo chosen from the photo library.

I could do that.. when the photo is captured from camera, With the below snippet of code in Cordova.

    navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
    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);
}

But, what should i do to get the base64 image data when the photo gets chosen from library?

like image 816
Revathy Durairajan Avatar asked Jun 25 '12 11:06

Revathy Durairajan


3 Answers

function encodeImageUri(imageUri)
{
     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=imageUri;
     var dataURL = c.toDataURL("image/jpeg");
     return dataURL;
}

I have no solution in PhoneGap for this. So all I need is the base64 format of the image which has been chosen by user from their photo library. So I placed that image on canvas and toDataUrl() gave me the very format :-)

like image 84
Revathy Durairajan Avatar answered Nov 23 '22 22:11

Revathy Durairajan


You just need to tell it to pick from the photo library:

navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
    destinationType: Camera.DestinationType.DATA_URL,
    sourceType : Camera.PictureSourceType.PHOTOLIBRARY
}); 

Please be aware that loading a large base 64 encoded image may just cause and out of memory error in your app. Wherever possible use the FILE_URI to get your photo.

like image 43
Simon MacDonald Avatar answered Nov 23 '22 21:11

Simon MacDonald


Its the good way to get image in base64 but when is show base64 string returned by this function. It display me a white image. My code is as follows

var smallImage = document.getElementById('smallImage');
                smallImage.src = encodeImageUri(imageURI);
like image 42
Awais Rai Avatar answered Nov 23 '22 20:11

Awais Rai