Search code examples
androidiosblackberrycordovabase64

Get Base64 from imageURI with PhoneGap


I'm trying to get the base64 from an image that picked from the album on my phone, but I cannot make it work:

I tried this:

window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
    console.log("0");
    fileSystem.root.getFile(imageURI, null, function(fileEntry) {
        console.log("1");
        fileEntry.file(function(file) {
            console.log("2");
            var reader = new FileReader();
            reader.onloadend = function(evt) {
                console.log("Read complete!");
                image64.value = Base64.encode(evt.target.result);
            };
            reader.readAsText(file);
        }, failFile);
    }, failFile);
}, failSystem);

Although the image is displayed correctly.. I receive an error from this function:

fileSystem.root.getFile(imageURI, null, function(fileEntry)

And the error is: FileError.ENCODING_ERR

I know that code doesn't look pretty. But I don't know how to get the Base64 encoding from an imageURI.


Solution

  • I found the solution in Google groups. I modified it a little bit and this is the result:

    var gotFileEntry = function(fileEntry) { 
        console.log("got image file entry: " +  fileEntry.fullPath); 
        fileEntry.file( function(file) {
            var reader = new FileReader();
            reader.onloadend = function(evt) {
                console.log("Read complete!");
                image64.value = Base64.encode(evt.target.result);
            };
            reader.readAsText(file);
        }, failFile);
    };
    
    window.resolveLocalFileSystemURI(imageURI, gotFileEntry, failSystem); 
    

    NOTE: It takes about 20 seconds to read a normal 5MPixel image and another 10-15 to Base64 encode it.