Skip to content

Instantly share code, notes, and snippets.

@kosinix
Created June 8, 2016 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kosinix/06cd3b020a3bb0bb0b46fe5340786e99 to your computer and use it in GitHub Desktop.
Save kosinix/06cd3b020a3bb0bb0b46fe5340786e99 to your computer and use it in GitHub Desktop.
Desaturate an image by a factor
<?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);
@kosinix
Copy link
Author

kosinix commented Jun 13, 2016

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;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment