javascript 将图像URL转换为base64 - CORS问题

8tntrjer  于 2023-08-02  发布在  Java
关注(0)|答案(1)|浏览(108)

我正在尝试使用pdfmake将一些图像嵌入到PDF中。为此,我需要对图像使用dataURI。

this.getDataUri = (url) => {
  var defer = $q.defer();

  var image = new Image();
  image.setAttribute('crossOrigin', '');
  image.src = url;

  image.onload = function() {
    var canvas = document.createElement('canvas');
    canvas.width = this.naturalWidth;
    canvas.height = this.naturalHeight;

    canvas.getContext('2d').drawImage(this, 0, 0);
    defer.resolve(canvas.toDataURL('image/png'));
  };

  image.onerror = function() {
    defer.reject();
  };

  return defer.promise;
}

字符串
我有一个函数可以将图像URL转换为我需要的内容,直到最近这一直工作得很好,现在我得到了这个错误:
第一个月
以下是我的S3存储桶的CORS设置:

{
  "CORSRules": [
    {
      "AllowedHeaders": [
        "*"
      ],
      "AllowedMethods": [
        "HEAD",
        "GET",
        "PUT",
        "POST"
      ],
      "AllowedOrigins": [
        "*"
      ]
    }
  ]
}


我能做些什么来解决这个问题吗?

vc9ivgsu

vc9ivgsu1#

与我一样,当尝试转换图像URL从s3亚马逊到基地64.我得到cors错误
试着这样

function getBase64FromImage(url, onSuccess, onError) {
    var proxyUrl = 'https://cors-anywhere.herokuapp.com/'
    url = proxyUrl + url 
    var xhr = new XMLHttpRequest();
 
    xhr.responseType = "arraybuffer";
    xhr.open("GET", url);
 
    xhr.onload = function () {
        var base64, binary, bytes, mediaType;
 
        bytes = new Uint8Array(xhr.response);
        //NOTE String.fromCharCode.apply(String, ...
        //may cause "Maximum call stack size exceeded"
        binary = [].map.call(bytes, function (byte) {
            return String.fromCharCode(byte);
        }).join('');
        mediaType = xhr.getResponseHeader('content-type');
        base64 = [
            'data:',
            mediaType ? mediaType + ';':'',
            'base64,',
            btoa(binary)
        ].join('');
        onSuccess(base64);
    };
    xhr.onerror = onError;
    xhr.send();
}

字符串

相关问题