Skip to content

Instantly share code, notes, and snippets.

@hlorand
Created July 24, 2015 00:40
Show Gist options
  • Save hlorand/853ee462ae1b6ebb3143 to your computer and use it in GitHub Desktop.
Save hlorand/853ee462ae1b6ebb3143 to your computer and use it in GitHub Desktop.
PHP gd png image opacity filter function
function filter_opacity( &$img, $opacity ) //params: image resource id, opacity in percentage (eg. 80)
{
if( !isset( $opacity ) )
{ return false; }
$opacity /= 100;
//get image width and height
$w = imagesx( $img );
$h = imagesy( $img );
//turn alpha blending off
imagealphablending( $img, false );
//find the most opaque pixel in the image (the one with the smallest alpha value)
$minalpha = 127;
for( $x = 0; $x < $w; $x++ )
for( $y = 0; $y < $h; $y++ )
{
$alpha = ( imagecolorat( $img, $x, $y ) >> 24 ) & 0xFF;
if( $alpha < $minalpha )
{ $minalpha = $alpha; }
}
//loop through image pixels and modify alpha for each
for( $x = 0; $x < $w; $x++ )
{
for( $y = 0; $y < $h; $y++ )
{
//get current alpha value (represents the TANSPARENCY!)
$colorxy = imagecolorat( $img, $x, $y );
$r = ($colorxy >> 16) & 0xFF;
$g = ($colorxy >> 8) & 0xFF;
$b = $colorxy & 0xFF;
if ($r + $g + $b == 0)
{
$opacity2 = 0;
$alpha = ( $colorxy >> 24 ) & 0xFF;
//calculate new alpha
if( $minalpha !== 127 )
{ $alpha = 127 + 127 * $opacity2 * ( $alpha - 127 ) / ( 127 - $minalpha ); }
else
{ $alpha += 127 * $opacity2; }
}
else if ($r + $g + $b == 3)
{ continue; }
else
{
$alpha = ( $colorxy >> 24 ) & 0xFF;
//calculate new alpha
if( $minalpha !== 127 )
{ $alpha = 127 + 127 * $opacity * ( $alpha - 127 ) / ( 127 - $minalpha ); }
else
{ $alpha += 127 * $opacity; }
}
//get the color index with new alpha
$alphacolorxy = imagecolorallocatealpha( $img, ( $colorxy >> 16 ) & 0xFF, ( $colorxy >> 8 ) & 0xFF, $colorxy & 0xFF, $alpha );
//set pixel with the new color + opacity
if( !imagesetpixel( $img, $x, $y, $alphacolorxy ) )
{ return false; }
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment