Get Image Color

Get average color of image via Javascript

AFAIK, the only way to do this is with <canvas/>...

DEMO V2: http://jsfiddle.net/xLF38/818/

Note, this will only work with images on the same domain and in browsers that support HTML5 canvas:

function getAverageRGB(imgEl) {

var blockSize = 5, // only visit every 5 pixels
defaultRGB = {r:0,g:0,b:0}, // for non-supporting envs
canvas = document.createElement('canvas'),
context = canvas.getContext && canvas.getContext('2d'),
data, width, height,
i = -4,
length,
rgb = {r:0,g:0,b:0},
count = 0;

if (!context) {
return defaultRGB;
}

height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height;
width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width;

context.drawImage(imgEl, 0, 0);

try {
data = context.getImageData(0, 0, width, height);
} catch(e) {
/* security error, img on diff domain */
return defaultRGB;
}

length = data.data.length;

while ( (i += blockSize * 4) < length ) {
++count;
rgb.r += data.data[i];
rgb.g += data.data[i+1];
rgb.b += data.data[i+2];
}

// ~~ used to floor values
rgb.r = ~~(rgb.r/count);
rgb.g = ~~(rgb.g/count);
rgb.b = ~~(rgb.b/count);

return rgb;

}

For IE, check out excanvas.

How can I get the pixel color value of an image in javascript?

There is a whole section on HTML spec for image manipulation.
https://html.spec.whatwg.org/#pixel-manipulation

But concretely, one possibility is to use the getImageData function : https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas#getting_the_pixel_data_for_a_context

This article helped me a lot for this kind of thing : https://hacks.mozilla.org/2011/12/faster-canvas-pixel-manipulation-with-typed-arrays/

Here my example of a basic implementation (I'm using Typescript for make it simpler):

function GetColorPixel(
context: CanvasRenderingContext2D,
x: number,
y: number
): Array<number> {
const imageData: Uint8ClampedArray = context.getImageData(x, y, 1, 1).data
const rgbColor: Array<number> = [imageData[0], imageData[1], imageData[2]]
return rgbColor
}

In this function, you need to pass the context of canvas for example



Related Topics



Leave a reply



Submit