trimImage ( resource $image , int $colour , int $tolerance )
trimImage() will return top-most, right-most, bottom-most and left-most positions of wanted pixels for an image (i.e. find minimum image area so you can then trim given colour from the outer edges of an image).
Parameters
image
An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().
colour
colour to be 'trimmed'. Allowable range 0 (black) to 255 (white). if null (or outside 0 - 255) will use top/left corner colour as default.
tolerance
Acceptable range +- from colour. 0 (trim only exact colour) to 255 (trim all colours).
Return Values
Returns an array of outermost pixels which are outside the tolerance range from colour.
array( int $top, int $right, int $bottom, int $left )
Example (and actual function)
<?php
function trimImage($im,$c,$t) {
if (!is_numeric($c) || $c < 0 || $c > 255) {
$rgb = imagecolorat($im, 2, 2); $r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$c = round(($r+$g+$b)/3); }
if (!is_numeric($t) || $t < 0 || $t > 255) $t = 10;
$w = imagesx($im); $h = imagesy($im); for($x = 0; $x < $w; $x++) {
for($y = 0; $y < $h; $y++) {
$rgb = imagecolorat($im, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
if (
($r < $c-$t || $r > $c+$t) && ($g < $c-$t || $g > $c+$t) && ($b < $c-$t || $b > $c+$t) ) {
$y_axis[$y] = $y;
$x_axis[$x] = $x;
}
}
}
sort($y_axis);
sort($x_axis);
$top = array_shift($y_axis); $right = array_pop($x_axis); $bottom = array_pop($y_axis); $left = array_shift($x_axis); return array($top,$right,$bottom,$left);
}
$image='test.jpg';
$im = imagecreatefromjpeg($image); $c = (isset($_GET[c])) ? $_GET[c] : null; $t = (isset($_GET[t])) ? $_GET[t] : null; list($t,$r,$b,$l) = trimImage($im,$c,$t); $w = $r-$l; $h = $b-$t; imagedestroy($im); $html_display = <<<HTM
<style type="text/css">
#stage {
position: relative;
float: left; // so it is the same size as the image it contains
}
#canvas {
border: solid 1px #FC3;
width: {$w}px;
height: {$h}px;
position: absolute;
top: {$t}px;
left: {$l}px;
}
img { border: solid 1px #EEE; }
</style>
HTM;
?>
<html>
<head>
<?=$html_display?>
</head>
<body>
<div id="stage">
<div id="canvas"></div>
<img src="test.jpg" />
</div>
</body>
</html>