Reputation: 25
I am using the cordova-plugin-camera
in order to access the camera in my hybrid app.
I need to capture the photo and send it for upload as base64.
When capturing a photo, I can specify the following:
destinationType: Camera.DestinationType.DATA_URL
which returns an image encoded as base64. However, DATA_URL can be very memory intensive and cause app crashes or out of memory errors (as mentioned in the plugin's documentation). Because of this, my app crashes on weaker devices, so using DATA_URL
is a no-go. Using the default FILE_URI
should solve this problem, but my backend is configured to only accept base64 encoded images.
My question is, is there a way to convert an image from FILE_URI to DATA_URL base64 encoding?
Upvotes: 0
Views: 754
Reputation: 711
To convert your FILE_URI to base64 data which is DATA_URL, you can do as below:
getFileContentAsBase64(FILE_URI, callback) {
window.resolveLocalFileSystemURL(path, gotFile, fail);
function fail(e) {
alert('Cannot found requested file');
}
function gotFile(fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function (e) {
var content = this.result;
callback(content);
};
// The most important point, use the readAsDatURL Method from the file plugin
reader.readAsDataURL(file);
});
}
}
This returns a promise, to get your base64 data :
this.getFileContentAsBase64(thisResult.filename, (base64Image) => {
// Then you'll be able to handle the image file as base64
});
PS : FILE_URI should look like file:///storage/0/android...
Upvotes: 0
Reputation: 10626
You could download the picture from the FILE_URI
and then you'd have to render the image in a canvas and then from the canvas, get the base64 using the canvas.toDataURL
method.
Upvotes: 0