Turn image into Base 64

2

I am transforming an image that I send by the camera in base64 but the image is all black, I do not know what is wrong, it follows my code below

app.encodeImageUri(mediaFiles[i].fullPath); //Aqui envio o caminho da minha imagem da seguinte maneira 'file:/storage/emulated/0/DCIM/Camera/140014212.jpg'

encodeImageUri: function (imageUri)
{
    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;
    var dataURL = c.toDataURL("image/jpeg");
    alert(dataURL);

    var tb1 = '<img src=' + dataURL + '>';
    document.getElementById("imgBase64").innerHTML = tb1;

    return dataURL;
},
    
asked by anonymous 21.08.2015 / 20:53

2 answers

1

I believe that doing so solves the black image problem:

dataURL.replace(/^data:image\/(png|jpg|jpeg);base64,/, "");
var tb1 = '<img src=' + dataURL + '>';
document.getElementById("imgBase64").innerHTML = tb1;

But if it does not scroll, here is a working example: link

    
21.08.2015 / 21:52
1

I was able to solve with the following code:

convertImgToBase64URL: function (url, nome,callback, outputFormat){
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var canvas = document.createElement('CANVAS'),
        ctx = canvas.getContext('2d'), dataURL;
        canvas.height = this.height;
        canvas.width = this.width;
        ctx.drawImage(this, 0, 0);
        dataURL = canvas.toDataURL(outputFormat);
        callback(dataURL);
        canvas = null; 
    };
    img.src = url;
},

The function call looks like this:

app.convertImgToBase64URL(anexo[aux], ext, function(base64Img){
           /* Aqui Voce coloca a ação que deseja */
        });
    
22.08.2015 / 00:15