Transforming Image into Base 64

Asked

Viewed 451 times

2

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

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;
},
  • Vinicius take a look at this post http://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript

  • Is there anything that isn’t working? Isn’t the return within the expected? What’s the question?

  • 1

    @Erloncharles got my comment, see if you’re more cheerful now

  • see this link: http://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript

2 answers

1

I believe that by doing this, solve the problem of the black image:

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

But if it doesn’t, here’s a working example: http://jsfiddle.net/handtrix/yvq5y/

1

I managed 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 went like this:

app.convertImgToBase64URL(anexo[aux], ext, function(base64Img){
           /* Aqui Voce coloca a ação que deseja */
        });
  • But I wonder if it would be possible to adapt the code to send videos and audios?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.