图片到base64 JavaScript

时间:2019-03-17 01:49:55

标签: javascript image canvas base64 data-uri

因此,我尝试使用HTML canvas元素获取外部图像URL并将其转换为Base64,以便从中提取颜色。我返回了base64字符串,但是当我检查输出时,它为空。这是我的代码:

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)

有没有更好的方法来解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以采用的另一种方法是,您可以执行HTTP请求,然后将响应转换为blob。 有错字,已固定

我使用服务器上的本地映像对此进行了测试,并成功。

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)
})

输出:

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

确保已启用 CORS 。因为如果未启用CORS,则会出现如下错误:

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.