Skip to content

Instantly share code, notes, and snippets.

@boazsender
Created March 21, 2010 21:01
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save boazsender/cf23f8bddb307ad4abd8 to your computer and use it in GitHub Desktop.
Save boazsender/cf23f8bddb307ad4abd8 to your computer and use it in GitHub Desktop.
<?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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment