note 82162 added to function.imagefilter
| From: | aiden dot mail at freemail dot hu | Date: | Sat, 29 Mar 2008 20:16:43 +0000 |
| Subject: | note 82162 added to function.imagefilter | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-137728@lists.php.net to get a copy of this message | ||
Function to change the transparency of a png image on the fly. Works only with PNG, and with a
browser supporting alpha channel.
The function stretches the opacity-range of the image, so that the most opaque pixel(s) will be set
to the given opacity. (Other opacity values in pixels are modified accordingly.)
Returns success or failure.
<?php
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 );
$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;
}
?>
Example for use:
<?php
$image = imagecreatefrompng( "img.png" );
filter_opacity( $image, 75 );
header( "content-type: image/png" );
imagepng( $image );
imagedestroy( $image );
?>
----
Server IP: 69.147.83.197
Probable Submitter: 77.234.81.252
----
Manual Page -- http://www.php.net/manual/en/function.imagefilter.php
Edit -- https://master.php.net/note/edit/82162
Del: integrated -- https://master.php.net/note/delete/82162/integrated
Del: useless -- https://master.php.net/note/delete/82162/useless
Del: bad code -- https://master.php.net/note/delete/82162/bad+code
Del: spam -- https://master.php.net/note/delete/82162/spam
Del: non-english -- https://master.php.net/note/delete/82162/non-english
Del: in docs -- https://master.php.net/note/delete/82162/in+docs
Del: other reasons-- https://master.php.net/note/delete/82162
Reject -- https://master.php.net/note/reject/82162
Search -- https://master.php.net/manage/user-notes.php