I have a function for trimming white areas around images that works something like
if(imagecolorat($img, $x, $top) != 0xFFFFFF) {
//sets where the top part of the image is trimmed
}
The problem is some images have an occasional stray pixel that is so near white that it's unnoticeable but screws up the cropping because it's not exactly 0xFFFFFF but 0xFFFEFF or something. How could I rewrite the above statement so that it evaluates true for those near white images, say down to 0xFDFDFD, obviously without testing for ever possible value.
$color = imagecolorat($img, $x, $top);
$color = array(
'red' => ($color >> 16) & 0xFF,
'green' => ($color >> 8) & 0xFF,
'blue' => ($color >> 0) & 0xFF,
);
if ($color['red'] >= 0xFD
&& $color['green'] >= 0xFD
&& $color['blue'] >= 0xFD) {
//sets where the top part of the image is trimmed
}
For a description of the operators used, please read:
To detect these off-white colors correctly you should convert from RGB color coordinates to HSV; in HSV, all off-whites have an S near 0 and a V near 100 (normalized). This question has an answer with PHP code to do the conversion, so with that code you 'd have:
$rgb = imagecolorat($img, $x, $top);
$hsv = RBG_TO_HSV(($rgb >> 16) & 0xFF, ($rgb >> 8) & 0xFF, $rgb & 0xFF);
if ($hsv['S'] < .05 && $hsv['V'] > .95) {
// color is off-white
}
You can tweak the constants .05
and .95
to relax or tighten the criteria as you like; you can also use an interactive color picker (e.g. this) to get a feel for how close to white the colors are for different values of S
and V
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With