wymsee / cordova-imagePicker

Cordova Plugin For Multiple Image Selection
MIT License
407 stars 858 forks source link

Possible to retrieve images as DATA_URL insted of FILE_URI? #112

Open andrzey opened 8 years ago

andrzey commented 8 years ago

I was wondering if there was possible to retrieve the images as a base64 encoded strings?

DarrylD commented 8 years ago

I too would like this, a nice amount of hassle to convert outside of the plugin.

andrzey commented 8 years ago

how where you able to convert outside of the plugin? I only are able to retrieve the fileuri and not the actual imagedata.

DarrylD commented 8 years ago

Here's something I stripped out my app, was pretty hacked together but, works for now

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');

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, '');
}
function encodeImageUri(imageUri) {
    var deferred = $q.defer();

    var c = document.createElement('canvas');
    var ctx = c.getContext('2d');
    var img = new Image();

    img.onload = function(){
        c.width = this.width;
        c.height = this.height;
        ctx.drawImage(img, 0,0);
    };
    img.src = imageUri;

    return getBase64Image(img);

}

encodeImageUri(imageUrlHere)

But, I think using readAsDataURL from http://ngcordova.com/docs/plugins/file/ would work better since it's encoding on the native layer. From my understanding...

tomercagan commented 8 years ago

See my answer to #116 (not sure how to link directly to answer). I initially tried with FileReader.readAsDataURL but it give corrupt images. Also note that if you intend to send the image to remote server you might be better off using FileTransfer plugin here.