未调用图像加载

问题描述 投票:4回答:2

我正在尝试从外部URL读取图像作为数据URL。这是我的代码

var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
img = new Image();

img.onload = function(){
    canvas.height = img.height;
    canvas.width = img.width;
    ctx.drawImage(img, 0, 0);
    console.log(canvas.toDataURL("image/jpeg"));
    canvas = null;
};
img.crossOrigin = 'anonymous';
img.src = "http://pierre.chachatelier.fr/programmation/images/mozodojo-original-image.jpg";

这里没有调用图像的加载。但是,当我删除img.crossOrigin = 'anonymous';时,会调用onload并且浏览器抛出错误SecurityError: The operation is insecure.此错误来自Mozilla。Chrome提供错误-

Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

无法像在Linux计算机上那样在IE上进行测试

我找不到代码的其他问题。

javascript cross-domain
2个回答
0
投票

您只能将canvas.toDataURL("image/jpeg")应用于项目中存在的文件。根据我的想法,您可以使用其他网站上的远程图像将其转换为base64图像。一种解决方案是,从要获取的网站保存图像,然后将canvas.toDataURL()应用于该保存的图像。


0
投票

我更改了代码。现在,我使用代码从服务器而不是图像URL发送字节:

URL u = new URL(url);
InputStream is = u.openStream();
byte[] = IOUtils.toByteArray(is);
© www.soinside.com 2019 - 2024. All rights reserved.