-1

So I'm trying to use the HTML canvas element to take an external image URL and convert it to Base64 so I can extract the colors from it. I'm getting back a base64 string but when I check the output it's blank. Here's my code:

var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = new Image();
    var imgData
    img.onload = function() {
        ctx.drawImage(img, 0, 0);
    };
    img.src = 'https://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png';
    imgData = c.toDataURL();
    console.log(imgData)

Is there a better way to approach this?

Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
moose
  • 21
  • 1
  • 4

1 Answers1

0

Another way you can approach this is, you can do a HTTP request and then convert the response to blob. Had a typo, fixed

I tested this using a local image on my server, and was successful.

convert = (image, callback) => {
    let request = new XMLHttpRequest();
    request.onload = () => {
        let reader = new FileReader();
        reader.onloadend = () => {
            callback(reader.result);
        };
        reader.readAsDataURL(request.response);
    };
    request.open('GET', image);
    request.responseType = 'blob';
    request.send();
};
convert('https://via.placeholder.com/350x150', (base64) => {
    console.log('Base64:', base64)
})

Output:

Base64:, data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJYAAACWBAMAAADOL2zRAAAAG1BMVEXMzMyWlpaqqqq3t7fFxcW+vr6xsbGjo6OcnJyLKnDGAAAACXBIWXMAAA7EAAAOxAGVKw4bAAABAElEQVRoge3SMW+DMBiE4YsxJqMJtHOTITPeOsLQnaodGImEUMZEkZhRUqn92f0MaTubtfeMh/QGHANEREREREREREREtIJJ0xbH299kp8l8FaGtLdTQ19HjofxZlJ0m1+eBKZcikd9PWtXC5DoDotRO04B9YOvFIXmXLy2jEbiqE6Df7DTleA5socLqvEFVxtJyrpZFWz/pHM2CVte0lS8g2eDe6prOyqPglhzROL+Xye4tmT4WvRcQ2/m81p+/rdguOi8Hc5L/8Qk4vhZzy08DduGt9eVQyP2qoTM1zi0/uf4hvBWf5c77e69Gf798y08L7j0RERERERERERH9P99ZpSVRivB/rgAAAABJRU5ErkJggg==

Make sure you have CORS enabled. Because if CORS is not enabled you will get an error as such:

Access to XMLHttpRequest at 'https://via.placeholder.com/350x150' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
ABC
  • 2,068
  • 1
  • 10
  • 21
  • not sure why your getting downvoted, this is actually super helpful! I specifically asked for other options. Thank you so much! This solved my problem. – moose Mar 17 '19 at 02:19
  • @MoussaBoussi no problem, just be careful about the CORS policies. I just put a test image at `http://localhost:8000/test.jpg` then that solved the CORS problem for testing. – ABC Mar 17 '19 at 02:20