了解canvas如何将图像转换为黑白图像

2023-12-06

我发现这个脚本用于将图像转换为黑白图像,效果很好,但我希望更好地理解代码。我将我的问题以注释的形式放在代码中。

谁能更详细地解释一下这里发生的事情:

function grayscale(src){ //Creates a canvas element with a grayscale version of the color image
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    var imgObj = new Image();
    imgObj.src = src;
    canvas.width = imgObj.width;
    canvas.height = imgObj.height; 
    ctx.drawImage(imgObj, 0, 0); //Are these CTX functions documented somewhere where I can see what parameters they require / what those parameters mean?
    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; //Why is this multiplied by 4?
            var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3; //Is this getting the average of the values of each channel R G and B, and converting them to BW(?)
            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();
}

  1. 与大多数函数一样,画布函数的描述见官方规范. Also, MDC对于更“非正式”的文章很有帮助。例如。这drawImageMDC 上的函数是here.

  2. The getImageData函数返回一个对象,其中包含一个包含所有像素的字节数据的数组。每个像素由 4 个字节描述:r, g, b and a.

    r, g and b是颜色分量(红色、绿色和蓝色),alpha 是不透明度。因此每个像素使用 4 个字节,因此像素的数据从pixel_index * 4.

  3. 是的,它是对值进行平均。因为在接下来的 3 行中r, g and b都设置为相同的值,您将获得每个像素的灰色(因为所有 3 个分量的数量相同)。

    基本上,对于所有像素,这都适用:r === g, g === b因而也r === b。其适用的颜色是灰度(0, 0, 0是黑人和255, 255, 255是白色的)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

了解canvas如何将图像转换为黑白图像 的相关文章

随机推荐