1

I am trying to load an image from a url and convert it to a base64 string.

All i get is a string but when I use it as the html source of the image, the images is always blank.

What am I doing wrong?

function getBase64Image(imgUrl) {
            var image = new Image();
            var canvas = document.createElement("canvas");
            var context = canvas.getContext('2d');
            image.src = imgUrl;
            context.drawImage(image,0,0);
            return canvas.toDataURL();
        }

The function returns the string.

Thank you.

Animesh
  • 1,005
  • 10
  • 20
Dany D
  • 1,189
  • 2
  • 18
  • 44
  • I haven't yet tried your code. But it might be as simple as inserting the canvas to the DOM first. Since it is detached from the DOM it might not load the image. – Rasmus May 16 '14 at 14:19
  • FYI: You'll need to wait for the image to be loaded. Here is how I works: http://jsfiddle.net/handtrix/YvQ5y/ – HaNdTriX Nov 28 '14 at 17:18

1 Answers1

0

Simple way to do that:

$image = file_get_content($url);
$result = "data:image/png;base64,". base64_encode($image);
daminufe
  • 924
  • 1
  • 7
  • 13
  • The OP wants an answer in Javascript. – Rasmus May 16 '14 at 14:12
  • Oh yeah. I didn't noticed it :) Nice explanation here: http://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript And here: http://stackoverflow.com/questions/19644035/how-to-convert-an-image-to-base64-in-javascript – daminufe May 16 '14 at 14:16
  • I use phonegap, maybe I can use the phoneGap file plugin? – Dany D May 16 '14 at 14:17
  • Here you go: https://gist.github.com/pamelafox/2173589 – daminufe May 16 '14 at 14:20