Files
skirogaining.krk-litvinov.cz/imagelightnessat.func.php

45 lines
1.5 KiB
PHP
Raw Normal View History

2022-01-13 22:50:25 +01:00
<?php
/* Computes the lightness of a pixel. Lightness is used in HSL notation, as well
* as in various operations on images. This function returns a normalized value
* for lightness between 0 and 1, inclusive (0.0 being black, 1.0 being white).
*
* double imagelightnessat(resource img, int x, int y)
* img An open image resource to operate on (true color or palette)
* x, y The coordinates of the pixel to work on
*
* by Jed Smith <?php $u = "jed"; $d = "bz"; printf("<%s@%s.%s>", $u, $u, $d) ?>
2022-01-13 23:09:36 +01:00
*/
function imagelightnessat($img, $x, $y) {
2022-01-14 03:34:46 +01:00
if (!$img instanceof \GdImage && !is_resource($img)) {
2022-01-13 23:09:36 +01:00
trigger_error('imagelightnessat(): supplied argument is not a valid '
. 'Image resource', E_USER_WARNING);
2022-01-13 22:50:25 +01:00
return 0.0;
}
$c = @imagecolorat($img, $x, $y);
2022-01-13 23:09:36 +01:00
if ($c === false) {
return false;
}
if (imageistruecolor($img)) {
2022-01-13 22:50:25 +01:00
$red = ($c >> 16) & 0xFF;
$green = ($c >> 8) & 0xFF;
$blue = $c & 0xFF;
2022-01-13 23:09:36 +01:00
} else {
2022-01-13 22:50:25 +01:00
$i = imagecolorsforindex($img, $c);
$red = $i['red'];
$green = $i['green'];
$blue = $i['blue'];
2022-01-13 23:09:36 +01:00
}
2022-01-13 22:50:25 +01:00
$m = min($red, $green, $blue);
$n = max($red, $green, $blue);
/* Because RGB isn't normalized in GD, we divide by 510 here.
* Lightness = (Max(RGB) + Min(RGB)) / 2
* But that's assuming red, green, and blue are 0 through 1 inclusive.
* Red, green, and blue are actually 0-255 (255 + 255 = 510).
*/
2022-01-13 23:09:36 +01:00
$lightness = (float) (($m + $n) / 510.0);
2022-01-13 22:50:25 +01:00
2022-01-13 23:09:36 +01:00
return $lightness;
}