错误在angularJS中将图像URL转换为Base64FromImageUrl时在控制台中显示

时间:2017-06-29 13:29:17

标签: javascript angularjs base64

我正在将图片网址转换为Base64FromImageUrl,但我的控制台出现了这样的错误。

  

访问图像   'http://160.114.10.19/voiceapi/Upload/UserProfile/b4d980b3-3e8e-4e26-913e-e79e4ce34f88.png'   来自“http://localhost:8383”的来源已被CORS政策阻止:   请求中不存在“Access-Control-Allow-Origin”标头   资源。因此不允许来源“http://localhost:8383”   访问。

我的js代码

function getBase64FromImageUrl(url) {
            var img = new Image();
            img.setAttribute('crossOrigin', 'Access-Control-Allow-Origin', 'anonymous');

            img.onload = function () {
                var canvas = document.createElement("canvas");
                canvas.width = this.width;
                canvas.height = this.height;
                var ctx = canvas.getContext("2d");
                ctx.drawImage(this, 0, 0);
                $scope.a = canvas.toDataURL("image/png");
            };
            img.src = url;
        }


getBase64FromImageUrl("http://160.114.10.19/voiceapi/Upload/UserProfile/b4d980b3-3e8e-4e26-913e-e79e4ce34f88.png");

1 个答案:

答案 0 :(得分:0)

如果img.setAttribute('crossOrigin', 'Anonymous');的情况不起作用,可能存在CORS限制(您尝试从您的不同域访问资源),这可以从后端修复。 例如,我尝试转换来自不同网站的2张图片,第一张不起作用,但第二张(来自gravatar.com)有效。所以错误不是来自JS代码本身。



function toDataURL(src, callback, outputFormat) {
  var img = new Image();
  img.crossOrigin = 'Anonymous';
  img.onload = function() {
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    var dataURL;
    canvas.height = this.height;
    canvas.width = this.width;
    ctx.drawImage(this, 0, 0);
    dataURL = canvas.toDataURL(outputFormat);
    callback(dataURL);
  };
  img.src = src;
  if (img.complete || img.complete === undefined) {
    img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
    img.src = src;
  }
}

toDataURL(
  'https://vaadin.com/documents/10187/33841/cors-deployment-setup-with-vaadin.png',
  function(dataUrl) {
    console.log('Src static.srcdn.com:', dataUrl)
  }
)

toDataURL(
  'https://www.gravatar.com/avatar/00000000000000000000000000000000?d=monsterid&f=y',
  function(dataUrl) {
    console.log('Src gravatar.com:', dataUrl)
  }
)