Thursday 28 July 2016

javascript - accessing cache pictures phonegap



I'm saving pictures in my application using the camera feature of Phonegap. When I try to get the file through its saved file_URI (that I got from the camera), the image doesn't load.





function toBase64(url) {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext('2d');
var img = new Image();

img.src = url;
if ( img.height != 0 ) {
var height = img.height, width = img.width;
canvas.height = height;
canvas.width = width;
ctx.drawImage(img, 0, 0, width, height);
try {
var dataURL = canvas.toDataURL("image/jpg");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

catch (err) { console.log("ERROR " + err);}
}
else {
alert("Wrong path!");
}
}



The images are saved in the cache folder of the application (/data/data/my.app/cache)




Any ideas of where the problem could be from ?


Answer



I fixed this issue and had to use the FileReader object of Phonegap.





var base64;
function toBase64(filename) {
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, function(fileSystem) {

// Filesystem's root is the cache folder of the application: /storage/emulated/0/Android/data/com.yourcompany.whatever
fileSystem.root.getFile(filename, null, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log(evt.target.result);
// Firing callback
base64 = evt.target.result;
};
reader.readAsDataURL(file);

}, fail);
}, fail);
}, fail);
// We wait until the reader was fully loaded and then we return the base64 encrypted data !
while ( base64 == "" ) {}
base64 = base64.replace(/^data:image\/(png|jpg|jpeg);base64,/, "");
return base64;
}




Don't think that the "while(base64 == "" ) {}" is a good practice though...



EDIT: I used the do_when method of this gentleman instead of the empty loop !


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...