6

I am developing a phonegap application and using the navigator.getPicture method to get the images.

The way I am getting the picture is:

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

function onSuccess(imageURI) {
    var image = document.getElementById('myImage');
    image.src = imageURI;
}

Just like the example in phonegap doc's.

I want to be able to use the imageURI and then convert it to image data in order to upload it later. (I don't want to use phonegap's FileTransfer)

So far I have tried both Get image data in JavaScript? and How can you encode a string to Base64 in JavaScript?

When I try the following,

function onSuccess(imageURI) {
    getBase64Image(imageURI);
}

function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
   ctx.drawImage(img, 0, 0);

   // Get the data-URL formatted image
   // Firefox supports PNG and JPEG. You could check img.src to
   // guess the original format, but be aware the using "image/jpg"
   // will re-encode the image.
   var dataURL = canvas.toDataURL("image/png");

   console.log(dataURL); //here is where I get 'data:,'       

   return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

And print dataURL before returning. I just get data:, as the content.

Any ideas on what I'm doing wrong?

Community
  • 1
  • 1
fabian
  • 111
  • 1
  • 10

1 Answers1

0

Well you can try getting it as a DATA_URL. Your mileage may vary as you could run into an out of memory error when the image is converted to a Base64 string.

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

function onSuccess(imageURI) {
    var image = document.getElementById('myImage');
    image.src = imageURI;
}

Alternatively you can use the FileReader.readAsDataURL().

The canvas.toDataURL method is not implemented on earlier versions of Android.

Simon MacDonald
  • 23,253
  • 5
  • 58
  • 74
  • Hi Simon, I tried doing the readAsDataURL but had no luck with it. I didn't want to use DATA_URL but I think it might be the only option. Thanks. – fabian Nov 07 '12 at 21:53