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 );
?>
imagefilter
(PHP 5)
imagefilter — Applique un filtre à une image
Description
bool imagefilter
( resource $image
, int $filtertype
[, int $arg1
[, int $arg2
[, int $arg3
[, int $arg4
]]]] )
imagefilter() applique le filtre filtertype à l'image en utilisant les paramètres args1 , args2 et args3 lorsque cela est nécessaire.
Liste de paramètres
- image
-
Une ressource d'image, retourné par une des fonctions de création d'images, comme imagecreatetruecolor().
- filtertype
-
Le paramètre filtertype peut prendre l'une des valeurs suivantes :
- IMG_FILTER_NEGATE : renverse toutes les couleurs de l'image.
- IMG_FILTER_GRAYSCALE : convertit l'image en grayscale.
- IMG_FILTER_BRIGHTNESS : modifie la luminosité de l'image. Utilisez le paramètre args1 pour définir la luminosité.
- IMG_FILTER_CONTRAST : modifie le contraste de l'image. Utilisez le paramètre args1 pour définir le contraste.
- IMG_FILTER_COLORIZE : Identique au paramètre IMG_FILTER_GRAYSCALE excepté que vous pouvez spécifier une couleur. Utilisez trois arguments séparés dans les paramètres args1 , args2 et args3 sous la forme red , blue , green et arg4 pour le canal alpha . L'intervalle pour chaque couleur est 0 - 255.
- IMG_FILTER_EDGEDETECT : utilise la détection des bords pour les mettre en évidence dans l'image.
- IMG_FILTER_EMBOSS : grave l'image en relief.
- IMG_FILTER_GAUSSIAN_BLUR : brouille l'image en utilisant la méthode gaussienne.
- IMG_FILTER_SELECTIVE_BLUR : brouille l'image.
- IMG_FILTER_MEAN_REMOVAL : son utilisation signifie le déplacement pour réaliser un effet "peu précis".
- IMG_FILTER_SMOOTH : rend l'image lissoir (smooth). Utilisez le paramètre args1 pour définir le degré de lissoir.
- arg1
-
- arg2
-
- arg3
-
Valeurs de retour
Cette fonction retourne TRUE en cas de succès, FALSE en cas d'échec.
Historique
| Version | Description |
|---|---|
| 5.2.5 | Le support du canal Alpha pour la constante IMG_FILTER_COLORIZE a été ajouté. |
Exemples
Exemple #1 Exemple avec imagefilter()
<?php
$im = imagecreatefrompng('dave.png');
if ($im && imagefilter($im, IMG_FILTER_GRAYSCALE)) {
echo 'Image convertie en grayscale.';
imagepng($im, 'dave.png');
} else {
echo 'La convertion en grayscale a échoué.';
}
imagedestroy($im);
?>
Exemple #2 Exemple avec imagefilter()
<?php
$im = imagecreatefrompng('sean.png');
if ($im && imagefilter($im, IMG_FILTER_BRIGHTNESS, 20)) {
echo 'La luminosité de l\'image a été modifiée.';
imagepng($im, 'sean.png');
} else {
echo 'Echec lors de la modification de la luminosité.';
}
imagedestroy($im);
?>
Exemple #3 Exemple avec imagefilter()
<?php
$im = imagecreatefrompng('philip.png');
/* R, G, B, donc 0, 255, 0 correspond au vert */
if ($im && imagefilter($im, IMG_FILTER_COLORIZE, 0, 255, 0)) {
echo 'L\'image a été ombragée en vert avec succès.';
imagepng($im, 'philip.png');
} else {
echo 'Echec lors de la modification de l\'ombrage.';
}
imagedestroy($im);
?>
Notes
Note: Cette fonction n'est disponible que si PHP est compilé avec la version embarquée de la bibliothèque GD.
imagefilter
aiden dot mail at freemail dot hu
29-Mar-2008 01:16
29-Mar-2008 01:16
Kae Cyphet
02-Dec-2007 04:23
02-Dec-2007 04:23
To solve that annoying problem of having to install a pre-compiled version of GD just to get imagefilter($image,IMAGE_FILTER_NEGATE) working.
here is an open source solution.
uses the standard stuff included in php when you uncomment 'extension=php_gd2.dll' in the php.ini file and there ya go!
Useage:
<?php
$im = imagecreatefromjpeg("my_fav_image.jpg");
header("Content-type: image/jpg");
imagejpeg(invertimage($im));
imagedestroy($im);
?>
'=================================
<?php
function int2rgb($myint)
{
return array('red' => 0xFF & ($myint >> 0x10), 'green' => 0xFF & ($myint >> 0x8), 'blue' => 0xFF & $myint);
}
function invertimage($im)
{
$wid = imagesx($im);
$hei = imagesy($im);
$im2 = imagecreatetruecolor($wid,$hei);
$i=0;
$j=0;
$rgb = array('red' => 0, 'green' => 0, 'blue' => 0);
$ref = 0;
for($i = 0;$i < $wid; $i++)
{
for($j = 0;$j < $hei; $j++)
{
$rgb = int2rgb(imagecolorat($im,$i,$j));
$ref = imagecolorallocate($im2,255 - intval($rgb['red']),255 - intval($rgb['green']),255 - intval($rgb['blue']));
imagesetpixel($im2,$i,$j,$ref);
}
}
return $im2;
}
?>
michaeln no at spam associationsplus ca
21-Nov-2007 08:11
21-Nov-2007 08:11
Note: applying IMG_FILTER_EMBOSS to text and using in a customization to the CAPTCHA image script in phpBB or a project of your own is a very good way to stop OCR-ing bots from getting through. Embossed serif fonts are fairly easy for the human eye to understand but to an OCR script it is extremely difficult because it seems to give it the illusion of 3D.
If you only allocate 2 or 3 colours in the image, it uses the background colour alot in the embossed text, which greatly contributes to this.
I made my own custom CAPTCHA script to stop phpBB post spam for a client site I was developing and I have gone from getting 2-3 new spam users created every day to zero.
Anything with the source code freely available out there right now is possible to be defeated by spammers once one of them stars sharing code with the other spammers, but if you run something at least someone custom, their bots will pass you over.
ssttoo at gmail dot com
13-Nov-2007 12:31
13-Nov-2007 12:31
Here's a page that shows the different filters in action
http://www.phpied.com/image-fun-with-php-part-2/
Also shows some quick ways to do sepia.
admin at phpgfx dot com
26-Aug-2007 09:52
26-Aug-2007 09:52
this is a sepia function using microsoft's definition
<?php
function imagesepia( $img ) {
$total = imagecolorstotal( $img );
for ( $i = 0; $i < $total; $i++ ) {
$index = imagecolorsforindex( $img, $i );
$red = ( $index["red"] * 0.393 + $index["green"] * 0.769 + $index["blue"] * 0.189 ) / 1.351;
$green = ( $index["red"] * 0.349 + $index["green"] * 0.686 + $index["blue"] * 0.168 ) / 1.203;
$blue = ( $index["red"] * 0.272 + $index["green"] * 0.534 + $index["blue"] * 0.131 ) / 2.140;
imagecolorset( $img, $i, $red, $green, $blue );
}
}
?>
webmaster at designsbykosi dot info
08-May-2007 12:56
08-May-2007 12:56
This will only work if you have php5. For php4, you'll have to use the sepia function set webmaster at qudi dot de suggested.
fananf at nerdshack dot com
16-Mar-2007 10:26
16-Mar-2007 10:26
If you're looking for fast sepia effect that can be used for on-the-fly thumbnails generation you can't use sophisticated functions. The faster and much better way than described by webmaster at qudi dot de in the note from 31-Jan-2006 is applying colorize filter AFTER grayscale.
<?php
(...)
imagefilter($yourimage, IMG_FILTER_GRAYSCALE); imagefilter($yourimage, IMG_FILTER_COLORIZE, 90, 60, 40);
(...)
?>
I used (90,60,40) for my sepia after couple of tests, however, if you need darker or lighter just check what suits you best.
trucex email over at gmail
14-Feb-2007 12:31
14-Feb-2007 12:31
It appears that imagefilter doesn't play nice with apha. If you run an imagefilter on a transparent image it'll return a black image...similar to a lot of Photoshop plugins do.
PanuWorld
14-Jan-2007 06:55
14-Jan-2007 06:55
The documentation misses the exact meaning and valid ranges of the arguments for ImageFilter(). According to the 5.2.0 sources the arguments are:
IMG_FILTER_BRIGHTNESS
-255 = min brightness, 0 = no change, +255 = max brightness
IMG_FILTER_CONTRAST
-100 = max contrast, 0 = no change, +100 = min contrast (note the direction!)
IMG_FILTER_COLORIZE
Adds (subtracts) specified RGB values to each pixel. The valid range for each color is -255...+255, not 0...255. The correct order is red, green, blue.
-255 = min, 0 = no change, +255 = max
This has not much to do with IMG_FILTER_GRAYSCALE.
IMG_FILTER_SMOOTH
Applies a 9-cell convolution matrix where center pixel has the weight arg1 and others weight of 1.0. The result is normalized by dividing the sum with arg1 + 8.0 (sum of the matrix).
any float is accepted, large value (in practice: 2048 or more) = no change
ImageFilter seem to return false if the argument(s) are out of range for the chosen filter.
nancy at hypertextdigital dot com
03-Aug-2006 02:16
03-Aug-2006 02:16
This routine was just what I was looking for, I wanted web admin users to be able to recolour their uploaded photos (to go with a news item) either a blue tint or sepia to match the appearance of other colours used on the website.
Using a form with a select box containing the RGB values, I can give them the option of either of the two tints or no colourization at all, plus resize their images to the viewing size and a thumbnail image on the fly without having to use any other image editing software.
santibari at fibertel dot com
27-Feb-2006 11:37
27-Feb-2006 11:37
A colorize algorithm wich preserves color luminosity (i.e black
will output black, and white will output white).
This works in PHP4 and is great for customizing interfaces
dinamically.
<?php
function colorize($img_src,$img_dest, $r, $g, $b)
{
if(!$im = imagecreatefromgif($img_src))
return "Could not use image $img_src";
//We will create a monochromatic palette based on
//the input color
//which will go from black to white
//Input color luminosity: this is equivalent to the
//position of the input color in the monochromatic
//palette
$lum_inp=round(255*($r+$g+$b)/765); //765=255*3
//We fill the palette entry with the input color at its
//corresponding position
$pal[$lum_inp]['r']=$r;
$pal[$lum_inp]['g']=$g;
$pal[$lum_inp]['b']=$b;
//Now we complete the palette, first we'll do it to
//the black,and then to the white.
//FROM input to black
//===================
//how many colors between black and input
$steps_to_black=$lum_inp;
//The step size for each component
if($steps_to_black)
{
$step_size_red=$r/$steps_to_black;
$step_size_green=$g/$steps_to_black;
$step_size_blue=$b/$steps_to_black;
}
for($i=$steps_to_black;$i>=0;$i--)
{
$pal[$steps_to_black-$i]['r']=$r-round($step_size_red*$i);
$pal[$steps_to_black-$i]['g']=$g-round($step_size_green*$i);
$pal[$steps_to_black-$i]['b']=$b-round($step_size_blue*$i);
}
//From input to white:
//===================
//how many colors between input and white
$steps_to_white=255-$lum_inp;
if($steps_to_white)
{
$step_size_red=(255-$r)/$steps_to_white;
$step_size_green=(255-$g)/$steps_to_white;
$step_size_blue=(255-$b)/$steps_to_white;
}
else
$step_size_red=$step_size_green=$step_size_blue=0;
//The step size for each component
for($i=($lum_inp+1);$i<=255;$i++)
{
$pal[$i]['r']=$r + round($step_size_red*($i-$lum_inp));
$pal[$i]['g']=$g + round($step_size_green*($i-$lum_inp));
$pal[$i]['b']=$b + round($step_size_blue*($i-$lum_inp));
}
//--- End of palette creation
//Now,let's change the original palette into the one we
//created
for($c = 0; $c < $palette_size; $c++)
{
$col = imagecolorsforindex($im, $c);
$lum_src=round(255*($col['red']+$col['green']
+$col['blue'])/765);
$col_out=$pal[$lum_src];
imagecolorset($im, $c, $col_out['r'],
$col_out['g'],
$col_out['b']);
}
//save the image file
imagepng($im,$img_dest);
imagedestroy($im);
}//end function colorize
?>
webmaster at qudi dot de
31-Jan-2006 06:53
31-Jan-2006 06:53
for a quick, ok-looking, sepia-effect (also in php4) I just use this little fellow, since a real implementation of sepia was just way too slow.
function pseudosepia(&$im,$percent){
$sx=imagesx($im);
$sy=imagesy($im);
$filter=imagecreatetruecolor($sx,$sy);
$c=imagecolorallocate($filter,100,50,50);
imagefilledrectangle($filter,0,0,$sx,$sy,$c);
imagecopymerge($im,$filter,0,0,0,0,$sx,$sy,$percent);
}
a php user at nowhere dot com
20-Dec-2005 12:48
20-Dec-2005 12:48
http://www.hudzilla.org/phpbook/read.php/11_2_15
for more detailed info, and some <i>arg</i> guidelines.
vdepizzol at hotmail dot com
04-Sep-2004 01:36
04-Sep-2004 01:36
Examples using imagefilter():
<?php
$im = imagecreatefrompng('dave.png');
if ($im && imagefilter($im, IMG_FILTER_GRAYSCALE)) {
echo 'Image converted to grayscale.';
imagepng($im, 'dave.png');
} else {
echo 'Conversion to grayscale failed.';
}
imagedestroy($im);
?>
/////////////////////////////
<?php
$im = imagecreatefrompng('sean.png');
if ($im && imagefilter($im, IMG_FILTER_BRIGHTNESS, 20)) {
echo 'Image brightness changed.';
imagepng($im, 'sean.png');
} else {
echo 'Image brightness change failed.';
}
imagedestroy($im);
?>
/////////////////////////////
<?php
$im = imagecreatefrompng('philip.png');
/* R, G, B, so 0, 255, 0 is green */
if ($im && imagefilter($im, IMG_FILTER_COLORIZE, 0, 255, 0)) {
echo 'Image successfully shaded green.';
imagepng($im, 'philip.png');
} else {
echo 'Green shading failed.';
}
imagedestroy($im);
?>
kees at tweakers dot net
20-Jul-2004 06:26
20-Jul-2004 06:26
From what i have been able to find from this function, it accepts the following arguments:
IMG_FILTER_NEGATE
IMG_FILTER_GRAYSCALE
IMG_FILTER_EDGEDETECT
IMG_FILTER_GAUSSIAN_BLUR
IMG_FILTER_SELECTIVE_BLUR
IMG_FILTER_EMBOSS
IMG_FILTER_MEAN_REMOVAL
The following arguments need one or more arguments.
IMG_FILTER_SMOOTH, -1924.124
IMG_FILTER_COLORIZE, -127.12, -127.98, 127
IMG_FILTER_CONTRAST, -90
IMG_FILTER_BRIGHTNESS, 98
I haven't tested them all, the names speak for themselves.
