Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: how to express "near white" as a color?

Tags:

php

rgb

gd

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.

like image 281
L84 Avatar asked Oct 31 '12 13:10

L84


2 Answers

$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:

  • PHP - Two unusual operators used together to get image pixel color, please explain
like image 182
Alin Roman Avatar answered Oct 28 '22 14:10

Alin Roman


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.

like image 3
Jon Avatar answered Oct 28 '22 15:10

Jon