added dominant color function

This commit is contained in:
Lokesh Dhakar
2011-11-03 01:02:12 -04:00
parent e1569c40fe
commit 3b704e8bc4
10 changed files with 79 additions and 23 deletions

View File

@@ -3,18 +3,25 @@ $(document).ready(function(){
$('img').each(function(index){
var averageRGB = getAverageRGB(this);
var dominantColor = getDominantColor(this);
var areaPalette = createAreaBasedPalette(this, 9);
var medianPalette = createMedianCutPalette(this, 10);
var imageSection = $(this).closest('.imageSection'),
swatchEl;
var imageSection = $(this).closest('.imageSection');
swatchEl = $('<div>', {
var swatchEl = $('<div>', {
'class': 'swatch'
}).css('background-color','rgba('+averageRGB.r+','+averageRGB.g+ ','+averageRGB.b+', 1)');
imageSection.find('.averageRGB').append(swatchEl);
swatchEl = $('<div>', {
'class': 'swatch'
}).css('background-color','rgba('+dominantColor.r+','+dominantColor.g+ ','+dominantColor.b+', 1)');
imageSection.find('.dominantColor').append(swatchEl);
var areaBasedPalette = imageSection.find('.areaBasedPalette');
$.each(areaPalette, function(index, value){

View File

@@ -18,10 +18,13 @@ function getAverageRGB(sourceImage) {
// Add all the red values together, repeat for blue and green.
// Last step, divide by the number of pixels checked to get average.
while ( (i += sampleSize * 4) < pixelCount ) {
++count;
rgb.r += pixels[i];
rgb.g += pixels[i+1];
rgb.b += pixels[i+2];
// if pixel is mostly opaque
if(pixels[i+3] > 125){
++count;
rgb.r += pixels[i];
rgb.g += pixels[i+1];
rgb.b += pixels[i+2];
}
}
rgb.r = Math.floor(rgb.r/count);
@@ -33,6 +36,33 @@ function getAverageRGB(sourceImage) {
function getDominantColor(sourceImage){
var palette = [];
// Create custom CanvasImage object
var image = new CanvasImage(sourceImage),
imageData = image.getImageData(),
pixels = imageData.data,
pixelCount = image.getPixelCount();
var pixelArray = [];
for (var i = 0; i < pixelCount; i++) {
// If pixel is mostly opaque
if(pixels[i*4+3] >= 125){
pixelArray.push( [pixels[i*4], pixels[i*4+1], pixels[i*4+2]]);
}
};
var cmap = MMCQ.quantize(pixelArray, 5);
var newPalette = cmap.palette();
return {r: newPalette[0][0], g: newPalette[0][1], b: newPalette[0][2]};
}
function createAreaBasedPalette(sourceImage, colorCount){
var palette = [];
@@ -98,7 +128,10 @@ function createMedianCutPalette(sourceImage, colorCount){
var pixelArray = [];
for (var i = 0; i < pixelCount; i++) {
pixelArray.push( [pixels[i*4], pixels[i*4+1], pixels[i*4+2]]);
// If pixel is mostly opaque
if(pixels[i*4+3] >= 125){
pixelArray.push( [pixels[i*4], pixels[i*4+1], pixels[i*4+2]]);
}
};
var cmap = MMCQ.quantize(pixelArray, colorCount);