Skip to content

Instantly share code, notes, and snippets.

@leibovic
Created June 9, 2011 16:27
Show Gist options
  • Select an option

  • Save leibovic/1017111 to your computer and use it in GitHub Desktop.

Select an option

Save leibovic/1017111 to your computer and use it in GitHub Desktop.

Revisions

  1. leibovic revised this gist Jun 9, 2011. 1 changed file with 5 additions and 7 deletions.
    12 changes: 5 additions & 7 deletions dominant-color.js
    Original file line number Diff line number Diff line change
    @@ -8,6 +8,8 @@ function getDominantColor(aImg) {

    // keep track of how many times a color appears in the image
    let colorCount = {};
    let maxCount = 0;
    let dominantColor = "";

    // data is an array of a series of 4 one-byte values representing the rgba values of each pixel
    let data = context.getImageData(0, 0, aImg.height, aImg.width).data;
    @@ -23,18 +25,14 @@ function getDominantColor(aImg) {
    continue;

    colorCount[color] = colorCount[color] ? colorCount[color] + 1 : 1;
    }

    // find the color that appears the most times
    let maxCount = 0;
    let siteColor = "";
    for (let color in colorCount) {
    // keep track of the color that appears the most times
    if (colorCount[color] > maxCount) {
    maxCount = colorCount[color];
    siteColor = color;
    dominantColor = color;
    }
    }

    let rgb = siteColor.split(",");
    let rgb = dominantColor.split(",");
    return rgb;
    }
  2. leibovic created this gist Jun 9, 2011.
    40 changes: 40 additions & 0 deletions dominant-color.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    function getDominantColor(aImg) {
    let canvas = document.createElement("canvas");
    canvas.height = aImg.height;
    canvas.width = aImg.width;

    let context = canvas.getContext("2d");
    context.drawImage(aImg, 0, 0);

    // keep track of how many times a color appears in the image
    let colorCount = {};

    // data is an array of a series of 4 one-byte values representing the rgba values of each pixel
    let data = context.getImageData(0, 0, aImg.height, aImg.width).data;

    for (let i = 0; i < data.length; i += 4) {
    // ignore transparent pixels
    if (data[i+3] == 0)
    continue;

    let color = data[i] + "," + data[i+1] + "," + data[i+2];
    // ignore white
    if (color == "255,255,255")
    continue;

    colorCount[color] = colorCount[color] ? colorCount[color] + 1 : 1;
    }

    // find the color that appears the most times
    let maxCount = 0;
    let siteColor = "";
    for (let color in colorCount) {
    if (colorCount[color] > maxCount) {
    maxCount = colorCount[color];
    siteColor = color;
    }
    }

    let rgb = siteColor.split(",");
    return rgb;
    }