0

I have the following

HTML

<img id="preview1" crossorigin="anonymous" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">

JS

var img = document.getElementById("preview1");
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.width;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
var result = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
console.log(result)

For some reason, when I paste the result (base64) in an img src it shows nothing. Also when I paste the result (base64) as a url, it shows nothing.

When I use use input="file" and use FileReader() to get the file. it works fine.

Is it a better way to grab a remote file and convert to a working base64?

1 Answers1

-1

EDIT: The code bellow will NOT work with a remote image. Sorry, was running the Chrome with the '--disable-web-security' flag.

I have made a simple JsFiddle with a working version of what you want.

function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    // Get the data-URL formatted image
    // Firefox supports PNG and JPEG. You could check img.src to
    // guess the original format, but be aware the using "image/jpg"
    // will re-encode the image.
    return canvas.toDataURL("image/png");
}

var im = new Image();
im.onload = function(ev) {
    var im = ev.target;
    var img = document.getElementById("preview1");
    img.src = getBase64Image(im);
}
im.src = "http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG"

Oh, and I shamelessly copied the getBase64Image method from this other answer

Community
  • 1
  • 1
Victor Gomes
  • 184
  • 7
  • 15
  • This won't work because of the different domain. (This is exactly why this question was asked: "Is it possible to base64 a *remote* image?") – Derek 朕會功夫 Sep 30 '14 at 03:54
  • getting the cors error in the fiddle. Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. –  Sep 30 '14 at 04:09
  • Oh I see... I was developing a webapp of my own and was running Chrome with the '--disable-web-security' flag. Useful during development. Indeed this will not work with a CORS request in an usual environment. – Victor Gomes Sep 30 '14 at 04:15