如何使用 JavaScript 从图像区域获取 RGB 数据

How to get the RGB data from an area of image with JavaScript

我无法从图像中获取 RGB 数据,我正在做的是获取区域的 de x、y、宽度和高度,所以,我想知道该区域的 RGB 数据,没有面积的像素。

我试图将 canvas 与 getImageData 一起使用,但它 returns 只是一个像素,我正在使用一个库来获取 x、y、w 和 h 的参数,我的图像大小和我的一样 canvas

我就是这么做的

const canvas2 = document.getElementById('canvasIMG'); //Get the canvas
const img2 = document.getElementById('imagen');//Get the image
const ctxImagen = canvas2.getContext('2d');//Get the context of canvas
ctxImagen.drawImage(img, 0, 0);
var rgb = ctxImagen.getImageData(ejex,ejey,1000, 1000).data; //"ejex" is the x coordinate and "ejey" is y coordinate, and 1000 is the width and the height, i tried to change the values of w and h, and is the same always, I download a RGB image, and in the console just print the color of both uppset corners
console.log("red ", rgb[0]);
console.log("green ", rgb[1]);
console.log("blue ", rgb[2]);
console.log("alpha ", rgb[3]);

我没有收到任何错误消息。

要获取区域像素的平均值,您应该获取区域然后自己计算平均值(我在这里制作了一个渐变,因为我实际上无法将图像导入 canvas在 Stack Overflow 上,因为那将是一个 CORS 问题):

const canvas = document.createElement( 'canvas' );
const ctx = canvas.getContext( '2d' );
const gradient = ctx.createLinearGradient( 0, 0, 500, 500 );

gradient.addColorStop( 0, 'red' );
gradient.addColorStop( 1, 'blue' );

document.body.appendChild( canvas );

canvas.width = canvas.height = 500;
ctx.fillStyle = gradient;
ctx.fillRect( 0, 0, 500, 500 );

const data = ctx.getImageData( 0, 0, 500, 500).data;
const average = { r: 0, g: 0, b: 0, a: 0 }; // Creates an object to count all the values up
const pixels = data.length / 4; // The actual amount of pixels read

// Now lets loop through all the pixels. They are a flat array of values for [r,g,b,a] sequently from top left to bottom right. So every four entries forms one pixel.

for( let i = 0; i < data.length; i += 4 ){
   
   // Add all the averages to their corresponding counters.
   average.r += data[i];
   average.g += data[i+1];
   average.b += data[i+2];
   average.a += data[i+3];
  
}

// Now just divide the count with the amount of pixels to get it as one value. ROund it, as RGB is Integers only, and divide the A by 255 as the alpha value is a Float between 0 and 1.

average.r = Math.floor( average.r / pixels );
average.g = Math.floor( average.g / pixels );
average.b = Math.floor( average.b / pixels );
average.a = Math.floor( average.a / pixels ) / 255;

// Lets draw a small square with the final average pixel color:

ctx.fillStyle = `rgba(${average.r},${average.g},${average.b},${average.a})`;
ctx.fillRect( 20, 20, 50, 50 );
ctx.strokeStyle = 'white';
ctx.lineWidth = 5;
ctx.strokeRect( 20, 20, 50, 50 );