Created
June 8, 2016 07:04
-
-
Save kosinix/06cd3b020a3bb0bb0b46fe5340786e99 to your computer and use it in GitHub Desktop.
Desaturate an image by a factor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$image = imagecreatefrompng( 'trees.png' ); | |
$width = imagesx( $image ); | |
$height = imagesy( $image ); | |
// Create | |
$output = imagecreatetruecolor($width, $height); | |
for( $y = 0; $y < $height; $y++ ){ | |
for( $x = 0; $x < $width; $x++ ){ | |
// Get pixel | |
$rgb = imagecolorat( $image, $x, $y ); | |
$r = ($rgb >> 16) & 0xFF; | |
$g = ($rgb >> 8) & 0xFF; | |
$b = $rgb & 0xFF; | |
$f = 1; // desaturate by 100% | |
$L = ( 0.3 * $r ) + ( 0.6 * $g ) + ( 0.1 * $b ); | |
$r = $r + $f * ($L - $r); | |
$g = $g + $f * ($L - $g); | |
$b = $b + $f * ($L - $b); | |
imagesetpixel( $output, $x, $y, imagecolorallocate( $output, $r, $g, $b )); | |
} | |
} | |
header('Content-Type: image/png'); | |
imagepng($output); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Explanation:
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
($rgb >> 16) means to convert $rgb to binary and shift 16 bits to the right, discarding the bits.
($rgb >> 16) & 0xFF means to do a bitwise AND operation on the shifted binary with the binary of 0xFF. 0xFF may as well be 255 and the results will be the same: ($rgb >> 16) & 255
What ($rgb >> 16) & 0xFF does is get the first 8 bits of the shifted $rgb. The rest are discarded.
See: http://code.tutsplus.com/articles/understanding-bitwise-operators--active-11301
Note alpha can be fetched with just imagecolorat without using imagecolorindex:
$transparency = ($color >> 24) & 0x7F;