secret
Last active

  • Download Gist
Determine Dominant Color
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
<?php
$file = $_GET['file'];
if (!$_GET['file']){
$file = 'http://labs.suredev.com/stuff/speckles.jpg';
}
 
$image = imagecreatefromjpeg($file);
$width = imagesx($image);
$height = imagesy($image);
$pixels = $width * $height;
$pixel = $internpixel = 0;
$scores = $dist = $distances = array();
 
for($x = 0; $x < $width; $x++){
for($y = 0; $y < $height; $y++,$pixel++){
 
$rgb = imagecolorat($image, $x, $y);
$color = imagecolorsforindex($image, $rgb);
 
$colorkey = join(array_slice($color, 0, 3), ",");
$pixelkey = $x . "," . $y;
 
for($x2 = 0; $x2 < $width; $x2++){
for($y2 = 0; $y2 < $height; $y2++){
$internpixel++;
$rgb2 = imagecolorat($image, $x2, $y2);
$color2 = imagecolorsforindex($image, $rgb2);
$dist[] = sqrt(pow(($color2['red'] - $color['red']), 2) + pow(($color2['green'] - $color['green']), 2) + pow(($color2['blue'] - $color['blue']), 2));
$computeddists = array_sum($dist);
unset($dist);
}
}
$distances[$colorkey] = $computeddists;
}
}
asort($distances, SORT_NUMERIC);
$topcolor = array_shift(array_keys($distances));
?>
 
<html>
<head>
<title>Find the most common color</title>
</head>
<body>
<form action='' method='get'>
<label>Path to img on the www</label> <input type='text' name='file'><input type='submit'>
</form>
<img src='<?php echo $file ?>'>
<br />
<h1>The most common color is:</h1>
<div style='background: rgb(<?php echo $topcolor ?>); height: 100px;width:100px'></div>
 
<hr/>
 
 
<pre>
<?php
echo 'pixel: ' . $pixel . '<br />';
echo 'block: ' . $block . '<br />';
echo 'internpixel: ' . $internpixel . '<br />';
echo 'pixels: ' . $pixels . '<br />';
echo 'x: ' . $x . '<br />';
echo 'y: ' . $y . '<br />';
echo 'top color index: ' . $topcolor . '<br />';
echo 'distances: ' . print_r($distances) . '<br />';
?>
</pre>
 
 
</body>
</html>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.