0

I am using this popular code from StackOverflow, and it works fine in terms of setting an image.src to this base64 URL, but I can't see the actual URL for some reason. I put arrows to point where my errors are. This is the weird part though: when I have an img element on my HTML page and I set the img.src property to the dataURL created from this method, it works perfectly. How do I extract and see the string?

// Code taken from MatthewCrumley (http://stackoverflow.com/a/934925/298479)
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");
// alert(canvas.toDataURL("image/png"); <-- THIS PRINTS A NORMAL DATA URL FINE
ctx.drawImage(img, 0, 0);
// alert(canvas.toDataURL("image/png"); <-- THIS PRINTS AN EMPTY STRING (BLANK ALERT PAGE)

// 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.
var dataURL = canvas.toDataURL("image/png");

return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
ThePumpkinMaster
  • 2,181
  • 5
  • 22
  • 31
  • 1
    I think it's because the same origin policy. If the image is external, the browser won't allow you to access the image. – Oriol Jul 23 '15 at 00:38
  • What do you mean the same origin policy? Then how do I access the dataURL string? – ThePumpkinMaster Jul 23 '15 at 00:42
  • [Same-origin policy](https://en.wikipedia.org/wiki/Same-origin_policy). If the image is external, you can't. – Oriol Jul 23 '15 at 00:52
  • There has to be SOME way to access it right? – ThePumpkinMaster Jul 23 '15 at 01:39
  • Yes you could use an XMLHttpRequest, with the responseType set to `blob` and then use URL.createObjectURL() to bypass the CORS restriction, but this will be limited to IE10+ – Kaiido Jul 23 '15 at 02:16
  • @Kaiido But AJAX is also restricted to the same origin policy, so I think that won't work. – Oriol Jul 23 '15 at 11:47
  • @Oriol no it does [see fiddle](http://jsfiddle.net/srx55dx6/) – Kaiido Jul 23 '15 at 11:48
  • @Oriol The cross-origin policy does in fact taint the canvas. But here, we first transform it to a data URL from the blob, then we draw it back to the canvas, so there is no more crossorigin involved, since it comes from a blob url. – Kaiido Jul 23 '15 at 11:53
  • 1
    @Kaiido OK, in your example it works because the image is sent with `Access-Control-Allow-Origin: *`. But in general AJAX connections can't be established to other domains ([demo](http://jsfiddle.net/srx55dx6/1/)). – Oriol Jul 23 '15 at 12:08
  • @Oriol, you're right. I should then edit this first comment to include that it would be a workaround only for servers with `Access-Control-Allow-Origin: *` which also taint the canvases. – Kaiido Jul 23 '15 at 12:14

0 Answers0