javascript - Get average outer pixel color of image -
so want average color of outer pixels in image, give background of div image shown in, same color. won't have make images background color myself.
example: if image 100px x 100px
, check 5 outer pixels @ top of image, 5 outer pixels of right side of image, same left , bottom. 5 x 100 x 4 pixels, colors, check average , let js give div same background.
so if average color #000000
, div bg #000000
. if average #fafafa
, div bg #fafafa
you have use canvas this. require cors restrictions fulfilled though.
if it's matter of extracting pixels region want analyse, add , divide on number of pixels counted.
demo
var img = new image(); // load image img.crossorigin = ""; // need cors here... img.onload = function() { // when image has loaded: var div = document.queryselector("div"); div.appendchild(this); // add image dom (demo) div.style.background = analyse(img, 5); // bg color = result analyse } img.src = "http://i.imgur.com/rueqdje.png"; // image (cors enabled) function analyse(img, border) { var canvas = document.createelement("canvas"), // create canvas element ctx = canvas.getcontext("2d"), // context w = img.naturalwidth, // actual width.. h = img.naturalheight; canvas.width = w; // set canvas size canvas.height = h; ctx.drawimage(img, 0, 0); // draw in image // checks:, example: //if (border*2 > canvas.width || border*2 > canvas.height) throw "image small!"; // borders, avoid overlaps (though not matter in 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 , add 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 = 0, len = data.length; while(i < len) { r += data[i++]; // add red component etc. g += data[i++]; b += data[i++]; i++; cnt++; // count 1 pixel } } }
div {padding:30px}
<div></div>
Comments
Post a Comment