最新通知
远程在线图片转base64跨域问题
阅读次数:2190 最后编辑时间:2022年02月09日

概述

控制台提示

Access to image at '远程地址' from origin '本地地址' has been
blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is
present on the requested resource.

解决方案

将img绘制成canvas,再将canvas转换成base64的img流;

// 转换base64格式
function toBase64(image) {
    const canvas = document.createElement('canvas');
    canvas.width = image.width;
    canvas.height = image.height;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(image, 0, 0, image.width, image.height);
    const base64 = canvas.toDataURL('image/png');
    return base64;
}
// 把远程地址src转换成base64
function imageBase64(imgUrl) {
    const image = new Image();
    image.setAttribute('crossOrigin', 'anonymous'); // 解决跨域
    image.crossOrigin = '*';  // 解决跨域
    image.src = imgUrl + '?v=' + Math.random(); // 防止图片缓存
    image.onload = () => {
        var Base64Url = toBase64(image);
        console.log(Base64Url);
    };
}