获取图像的平均外部像素颜色

时间:2015-04-01 09:21:53

标签: javascript jquery css image

所以我想获得图像中外部像素的平均颜色,以给出图像显示的div的背景,颜色相同。因此,我不必自己制作所有图像背景颜色。

示例:如果图像为100px x 100px,则检查图像顶部的5个外部像素,图像右侧的5个外部像素,左侧和底部相同。您将得到5 x 100 x 4像素,获取颜色,检查平均值,让JS给div提供相同的背景。

因此,如果平均颜色为#000000,则div BG将为#000000。如果平均值为#FAFAFA,则div BG为#FAFAFA

1 个答案:

答案 0 :(得分:1)

你必须使用画布。这将要求履行CORS限制。

如果只是从你想要分析的区域中提取像素,可以加起来并除以你计算的像素数。

演示

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>