How to base64 encode an image in javascript

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

How do I get the image:

 navigator.camera.getPicture(onSuccess, onFail, { quality: 50, destinationType: Camera.DestinationType.FILE_URI }); function onSuccess(imageURI) { var image = document.getElementById('myImage'); image.src = imageURI; } 

In the same way as in the example with phone book documents.

I want to be able to use imageURI and then convert it to image data to load it later. (I do not want to use PhoneGap FileTransfer)

So far, have I tried both Get Image Data in JavaScript? and How can you encode Base64 string 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 out the dataURL before returning. I just get data:, as content.

Any ideas on what I'm doing wrong?

+6
source share
1 answer

Well, you can try to get it as DATA_URL. Your mileage may vary, as you may encounter a 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 FileReader.readAsDataURL () .

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

0
source

All Articles