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.

2
  • 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. Commented May 16, 2014 at 14:19
  • FYI: You'll need to wait for the image to be loaded. Here is how I works: jsfiddle.net/handtrix/YvQ5y Commented Nov 28, 2014 at 17:18

1 Answer 1

0

Simple way to do that:

$image = file_get_content($url);
$result = "data:image/png;base64,". base64_encode($image);
Sign up to request clarification or add additional context in comments.

4 Comments

The OP wants an answer in Javascript.
Oh yeah. I didn't noticed it :) Nice explanation here: stackoverflow.com/questions/6150289/… And here: stackoverflow.com/questions/19644035/…
I use phonegap, maybe I can use the phoneGap file plugin?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.