JSFiddle - React, Tailwind, and code Playground

by SamHasler

HTML

<body>
<div>
    <!--https://developer.mozilla.org/en/Canvas_tutorial/Using_images-->
    <img src="data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==" id="squares" height="30" width="30"/>
    <div id="info"></div>
</div>
<div>
    <!--http://www.websiteoptimization.com/speed/tweak/inline-images/-->
    <img...

JavaScript

function draw(img) {
    var canvas = document.createElement("canvas");
    var c = canvas.getContext('2d');
    c.width = canvas.width = img.width;
    c.height = canvas.height = img.height;
    c.clearRect(0, 0, c.width, c.height);
    c.drawImage(img, 0, 0, img.width , img.height);
    return c; // returns the context
}

// returns a map counting the frequency of colors 
// in the image on the canvas
function getColors(c) {
    var col, colors = {};
    var pixels, r, g, b, a;
    r = g = b = a = 0;
    pixels = c.getImageData(0, 0, c.width, c.height);
    for (var i = 0, data = pixels.data; i < data.length; i += 4) {
        r = data[i];
        g = data[i + 1];
        b = data[i + 2];
        a = data[i + 3]; // alpha
        // skip pixels >50% transparent
        if (a < (255 / 2))
            continue; 
        col = rgbToHex(r, g, b);
        if (!colors[col])
            colors[col] = 0;
        colors[col]++;
    }
    return colors;
}

function rgbToHex(r, g, b) {
    if (r > 255 || g > 255 || b > 255)
        throw "Invalid color component";
    return ((r << 16) | (g << 8) | b).toString(16);
}

// nicely formats hex values
function pad(hex) {
    return ("000000" + hex).slice(-6);
}

// blue squares
var info = document.getElementById("info");
var img = document.getElementById("squares");
var colors = getColors(draw(img));
for (var hex in colors) {
    info.innerHTML += "<li>" + pad(hex) + "->" + colors[hex];
}

// folder thing
var info2 = document.getElementById("info2");
var img2 = document.getElementById("dot");
var colors = getColors(draw(img2));
var arrColors = [];
for (var hex in colors) {
    arrColors.push([colors[hex],pad(hex)]);
}
var sortedColors = arrColors.sort(function(a,b){
    return b[0] - a[0];
})
sortedColors.forEach(function(c){
    info2.innerHTML += "<li>" + c[0] + " " + c[1];
})