Get the average outer pixel color of an image
So, I want to get the average color of the outer pixels in the image in order to give the background of the div that the image is depicted on to the same color. So I don't have to make all images the background color.
Example: If an image 100px x 100px
, you check the outer 5 pixels at the top of the image, the outer 5 pixels on the right side of the image, the same for the left and bottom. You will get 5 x 100 x 4 pixels, get the colors, check the average and let the JS give the div the same background.
So if the middle color the #000000
div BG will be #000000
. If average #FAFAFA
, div BG will be#FAFAFA
source to share
For this you need to use a canvas. This will require CORS restrictions.
If it's just a matter of extracting pixels from the region you want to analyze, add and divide the number of pixels counted.
Demo
var img = new Image(); // load an image
img.crossOrigin = ""; // we need CORS here...
img.onload = function() { // when image has loaded:
var div = document.querySelector("div");
div.appendChild(this); // add image to DOM (demo)
div.style.background = analyse(img, 5); // bg color = result from analyse
}
img.src = "http://i.imgur.com/rUeQDjE.png"; // some image (CORS enabled)
function analyse(img, border) {
var canvas = document.createElement("canvas"), // create a canvas element
ctx = canvas.getContext("2d"), // get context
w = img.naturalWidth, // get actual width..
h = img.naturalHeight;
canvas.width = w; // set canvas size
canvas.height = h;
ctx.drawImage(img, 0, 0); // draw in image
// do checks:, for example:
//if (border*2 > canvas.width || border*2 > canvas.height) throw "Image too small!";
// get borders, avoid overlaps (though it does not really matter in this case):
var top = ctx.getImageData(0, 0, w, border).data;
var left = ctx.getImageData(0, border, border, h - border*2).data;
var right = ctx.getImageData(w - border, border, border, h - border*2).data;
var bottom = ctx.getImageData(0, h - border, w, border).data;
var r = 0, g = 0, b = 0, cnt = 0;
// count pixels and add up color components: (see function below)
countBuffer(top);
countBuffer(left);
countBuffer(right);
countBuffer(bottom);
// calc average
r = (r / cnt + 0.5)|0;
g = (g / cnt + 0.5)|0;
b = (b / cnt + 0.5)|0;
return "rgb(" + r + "," + g + "," + b + ")";
function countBuffer(data) {
var i = 0, len = data.length;
while(i < len) {
r += data[i++]; // add red component etc.
g += data[i++];
b += data[i++];
i++;
cnt++; // count one pixel
}
}
}
div {padding:30px}
<div></div>
source to share