gpt4 book ai didi

javascript - 未捕获错误 : INDEX_SIZE_ERR: DOM Exception 1, getImageData

转载 作者:行者123 更新时间:2023-11-28 13:55:48 31 4
gpt4 key购买 nike

我正在使用以下代码将图像转换为灰度,在本地计算机上它很好,但是当我在服务器上部署相同的代码时,它会传递未捕获错误:INDEX_SIZE_ERR:DOM异常1我想知道是由于域不同,我不确定,但问题是由于“getImageData”引起的。另外,此问题仅在 chrome 上出现。

我读了很多帖子并尝试了很多,但似乎没有什么对我有用。

提前致谢...

function grayscale(img) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var imgObj = new Image();
imgObj.src = img;
canvas.width = imgObj.width;
canvas.height = imgObj.height;
ctx.drawImage(imgObj, 0, 0);
var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
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;
}
}
ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
return canvas.toDataURL();
}

最佳答案

这对我来说效果很好

// img is HTMLImageElement
function makeGreyScale(img) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var imgObj = new Image();
imgObj.src = img.src;
imgObj.onload = function(){
canvas.width = imgObj.width;
canvas.height = imgObj.height;
ctx.drawImage(imgObj, 0, 0);
var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);

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;
}
}
ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
img.src= canvas.toDataURL();
};
}

关于javascript - 未捕获错误 : INDEX_SIZE_ERR: DOM Exception 1, getImageData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8035215/

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