使用 JavaScript 确定图像是灰度还是彩色?

问题描述 投票:0回答:3

是否可以使用 JavaScript 确定给定图像是灰度图像还是彩色图像?

javascript image colors grayscale
3个回答
5
投票
  1. 将图像绘制到画布

  2. 循环图像数据

  3. 测试每个像素是否红色通道==绿色通道==蓝色通道(所有颜色通道具有相同的值)

如果所有像素都为真,则它是灰度,如果您击中第一个不符合条件的像素,您可以停止,它是彩色的。


2
投票

看看http://www.pixastic.com/lib/docs/actions/colorhistogram/

这将轻松提供您确定这一点所需的数据。


0
投票

function getimgDataImage(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    var context = canvas.getContext("2d");
    context.drawImage(img, 0, 0);

    return  context.getImageData(0, 0, canvas.width, canvas.height);
}
function IsItGrayscaleImage(img) {
    const imgData = getimgDataImage(img);
    var result = true;
    for (let i = 0; i < imgData.data.length; i += 4) {  
        if(imgData.data[i + 2] == imgData.data[i + 1] && imgData.data[i + 1] == imgData.data[i]){
            continue;
        }else{
            result = false;
            break;
        }
    }
    return result;
}
I have implemented zuloo suggestion. I hope it helps. The code first will take an img input and transfer it to imgData then it will loop to check if all colors have same values then it is a grayscale, if not it is not.

© www.soinside.com 2019 - 2024. All rights reserved.