This improves upon to my previous function (which only really worked on a few greyscale colours). Colour should now be a hexadecimal colour value. Colour and tolerance are now optional parameters.
trimImage ( resource $image [, str $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
Hexadecimal value of colour to be 'trimmed'. If omitted the top/left corner colour will be used as default.
tolerance
Acceptable range +- from colour. Allowable range 0 to 255. If omitted 10 will be used as default.
Return Values
Returns an array of outermost pixels which are beyond the tolerance range from colour.
array( int $top, int $right, int $bottom, int $left )
function trimImage($im,$c=null,$t=10) {
// if hex colour ($c) exists attempt to convert to decimal
if ($c) $rgb = @hexdec($c);
// if hexdec failed to get a value between black (0) and white (16777215)
// grab the colour from the top left corner (2 pixels in to avoid messy edges)
if (!is_numeric($rgb) || $rgb < 0 || $rgb > 16777215) $rgb = imagecolorat($im, 2, 2);
// split $rgb into red, green and blue
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
// make sure tolerance ($t) is a number between 0 - 255
if (!is_numeric($t) || $t < 0) $t = 0;
elseif ($t > 255) $t = 255;
$w = imagesx($im); $h = imagesy($im); // image width and height
for($x = 0; $x < $w; $x++) {
for($y = 0; $y < $h; $y++) {
$rgb = imagecolorat($im, $x, $y);
$red = ($rgb >> 16) & 0xFF;
$grn = ($rgb >> 8) & 0xFF;
$blu = $rgb & 0xFF;
if (
$red < $r-$t || $red > $r+$t || // not trim red (nor within tolerance)
$grn < $g-$t || $grn > $g+$t || // not trim green (nor within tolerance)
$blu < $b-$t || $blu > $b+$t // not trim blue (nor within tolerance)
) {
$y_axis[$y] = $y; $x_axis[$x] = $x; // wanted pixel coordinates stored
}
}
}
if (!$y_axis) $y_axis = $x_axis = array(0); // avoid errors if all pixels are trimmed
// sort so first and last occurances are at start and end
sort($y_axis); sort($x_axis);
$t = array_shift($y_axis); // first wanted pixel on Y axis (top)
$r = array_pop($x_axis); // last wanted pixel on X axis (right)
$b = array_pop($y_axis); // last wanted pixel on Y axis (bottom)
$l = array_shift($x_axis); // first wanted pixel on X axis (left)
return array($t,$r,$b,$l);
}