gpt4 book ai didi

javascript - 使用 js 将 img 转换为灰度面临安全错误

转载 作者:太空宇宙 更新时间:2023-11-04 11:53:28 25 4
gpt4 key购买 nike

我正在为旧手机做后备,我不能只使用 css,我找到了一种使用 js 将图像转换为灰度图像的方法。

http://jsfiddle.net/4uznof97/

  var imgObj = document.getElementById('templateBg');

function gray(imgObj) {
var canvas = document.createElement('canvas');
var canvasContext = canvas.getContext('2d');

var imgW = imgObj.width;
var imgH = imgObj.height;
canvas.width = imgW;
canvas.height = imgH;

canvasContext.drawImage(imgObj, 0, 0);
var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);

for (var y = 0; y < imgPixels.height; y++) {
for (var x = 0; x < imgPixels.width; x++) {
var i = (y * 4) * imgPixels.width + x * 4;
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}
}
canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
return canvas.toDataURL();
}
imgObj.src = gray(imgObj);

但是我得到了这个错误

Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.

最佳答案

您遇到了 Same Origin Policy因为它与 Canvas 相关:因为 Canvas 包含来自不同来源的内容,所以您的代码无法修改它。

来自canvas 2D spec :

The getImageData(sx, sy, sw, sh) method must, if the canvas element's origin-clean flag is set to false, throw a SecurityError exception

如果您可以控制这两个来源,您可以通过 Cross-Origin Resource Sharing 启用访问权限. (不过,我还没有在 Canvas 方面这样做。)

关于javascript - 使用 js 将 img 转换为灰度面临安全错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30452040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com