How to convert image with canvas to base64 using toDataURL?


I would like to know how I can convert to base64 an image that I have stored on my computer that has a url like this (folder / id / img.jpg)

So far I have tried this but it does not work for me, when I do the console.log and I see the data path in the console: it brings me and I give it click it goes all black without bringing any image

var c = document.createElement('canvas');

        c.width = 200;
        c.height = 200;

        var ctx = c.getContext('2d');

        var img = new Image();

            img.src = url;

            ctx.drawImage(img, 0, 0);

            var imgData = ctx.getImageData(0, 0, 200, 200);

            ctx.putImageData(imgData, 0, 0);

        var file = c.toDataURL();

        console.log( file );
asked by Alfonso Carrillo 20.12.2018 в 02:28

1 answer


It is likely that your image is not loaded. One solution would be to use img.onload in this way:

var img=new Image(); 
img.src = "carpeta/id/img.jpg"; 
img.onload = function() {. . . . }

Another solution would be to put your image somewhere in the document and use this image, something like this:

var img = document.getElementById("img");
ctx.drawImage( img, x, y ,w, h );

I like to put this image inside the canvas element since it is a way of hiding it. In your case you should find another way to hide it (if it bothers you) since you are creating the canvas element. I hope it's what you need.

answered by 20.12.2018 в 21:56