(PHP 5)
imagefilter — 对图像使用过滤器
$src_im
, int $filtertype
[, int $arg1
[, int $arg2
[, int $arg3
]]] )
imagefilter() 把过滤器
filtertype
应用到图像上,在需要时使用
arg1
,arg2
和
arg3
。
filtertype
可以是下列中的一个:
IMG_FILTER_NEGATE
:将图像中所有颜色反转。
IMG_FILTER_GRAYSCALE
:将图像转换为灰度的。
IMG_FILTER_BRIGHTNESS
:改变图像的亮度。用
arg1
设定亮度级别。
IMG_FILTER_CONTRAST
:改变图像的对比度。用
arg1
设定对比度级别。
IMG_FILTER_COLORIZE
:与
IMG_FILTER_GRAYSCALE
类似,不过可以指定颜色。用
arg1
,arg2
和
arg3
分别指定
red
,blue
和
green
。每种颜色范围是 0 到 255。
IMG_FILTER_EDGEDETECT
:用边缘检测来突出图像的边缘。
IMG_FILTER_EMBOSS
:使图像浮雕化。
IMG_FILTER_GAUSSIAN_BLUR
:用高斯算法模糊图像。
IMG_FILTER_SELECTIVE_BLUR
:模糊图像。
IMG_FILTER_MEAN_REMOVAL
:用平均移除法来达到轮廓效果。
IMG_FILTER_SMOOTH
:使图像更柔滑。用
arg1
设定柔滑级别。
Note: 此函数仅在与 GD 库捆绑编译的 PHP 版本中可用。
成功时返回 TRUE
, 或者在失败时返回 FALSE
。
Example #1 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);
?>
Example #2 imagefilter() 亮度例子
<?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);
?>
Example #3 imagefilter() 上彩例子
<?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);
?>
image
由图象创建函数(例如 imagecreatetruecolor())返回的图象资源。
filtertype
filtertype
can be one of the following:
IMG_FILTER_NEGATE
: Reverses all colors of
the image.
IMG_FILTER_GRAYSCALE
: Converts the image into
grayscale.
IMG_FILTER_BRIGHTNESS
: Changes the brightness
of the image. Use arg1
to set the level of
brightness.
IMG_FILTER_CONTRAST
: Changes the contrast of
the image. Use arg1
to set the level of
contrast.
IMG_FILTER_COLORIZE
: Like
IMG_FILTER_GRAYSCALE
, except you can specify the
color. Use arg1
, arg2
and
arg3
in the form of
red
, blue
,
green
and arg4
for the
alpha
channel. The range for each color is 0 to 255.
IMG_FILTER_EDGEDETECT
: Uses edge detection to
highlight the edges in the image.
IMG_FILTER_EMBOSS
: Embosses the image.
IMG_FILTER_GAUSSIAN_BLUR
: Blurs the image using
the Gaussian method.
IMG_FILTER_SELECTIVE_BLUR
: Blurs the image.
IMG_FILTER_MEAN_REMOVAL
: Uses mean removal to
achieve a "sketchy" effect.
IMG_FILTER_SMOOTH
: Makes the image smoother.
Use arg1
to set the level of smoothness.
IMG_FILTER_PIXELATE
: Applies pixelation effect
to the image, use arg1
to set the block size
and arg2
to set the pixelation effect mode.
arg1
IMG_FILTER_BRIGHTNESS
: Brightness level.
IMG_FILTER_CONTRAST
: Contrast level.
IMG_FILTER_COLORIZE
: 红色成分的值。
IMG_FILTER_SMOOTH
: Smoothness level.
IMG_FILTER_PIXELATE
: Block size in pixels.
arg2
IMG_FILTER_COLORIZE
: 绿色成分的值。
IMG_FILTER_PIXELATE
: Whether to use advanced pixelation
effect or not (defaults to FALSE
).
arg3
IMG_FILTER_COLORIZE
: 蓝色成分的值。
arg4
IMG_FILTER_COLORIZE
: Alpha channel, A value
between 0 and 127. 0 indicates completely opaque while 127 indicates
completely transparent.
成功时返回 TRUE
, 或者在失败时返回 FALSE
。
版本 | 说明 |
---|---|
5.3.0 |
Pixelation support (IMG_FILTER_PIXELATE ) was added.
|
5.2.5 |
Alpha support for IMG_FILTER_COLORIZE was added.
|
Example #4 imagefilter() grayscale example
<?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);
?>
Example #5 imagefilter() brightness example
<?php
$im = imagecreatefrompng('sean.png');
if($im && imagefilter($im, IMG_FILTER_BRIGHTNESS, 20))
{
echo 'Image brightness changed.';
imagepng($im, 'sean.png');
imagedestroy($im);
}
else
{
echo 'Image brightness change failed.';
}
?>
Example #6 imagefilter() colorize example
<?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');
imagedestroy($im);
}
else
{
echo 'Green shading failed.';
}
?>
Example #7 imagefilter() negate example
<?php
// Define our negate function so its portable for
// php versions without imagefilter()
function negate($im)
{
if(function_exists('imagefilter'))
{
return imagefilter($im, IMG_FILTER_NEGATE);
}
for($x = 0; $x < imagesx($im); ++$x)
{
for($y = 0; $y < imagesy($im); ++$y)
{
$index = imagecolorat($im, $x, $y);
$rgb = imagecolorsforindex($index);
$color = imagecolorallocate($im, 255 - $rgb['red'], 255 - $rgb['green'], 255 - $rgb['blue']);
imagesetpixel($im, $x, $y, $color);
}
}
return(true);
}
$im = imagecreatefromjpeg('kalle.jpg');
if($im && negate($im))
{
echo 'Image successfully converted to negative colors.';
imagejpeg($im, 'kalle.jpg', 100);
imagedestroy($im);
}
else
{
echo 'Converting to negative colors failed.';
}
?>
Example #8 imagefilter() pixelate example
<?php
// Load the PHP logo, we need to create two instances
// to show the differences
$logo1 = imagecreatefrompng('./php.png');
$logo2 = imagecreatefrompng('./php.png');
// Create the image instance we want to show the
// differences on
$output = imagecreatetruecolor(imagesx($logo1) * 2, imagesy($logo1));
// Apply pixelation to each instance, with a block
// size of 3
imagefilter($logo1, IMG_FILTER_PIXELATE, 3);
imagefilter($logo2, IMG_FILTER_PIXELATE, 3, true);
// Merge the differences onto the output image
imagecopy($output, $logo1, 0, 0, 0, 0, imagesx($logo1) - 1, imagesy($logo1) - 1);
imagecopy($output, $logo2, imagesx($logo2), 0, 0, 0, imagesx($logo2) - 1, imagesy($logo2) - 1);
imagedestroy($logo1);
imagedestroy($logo2);
// Output the differences
header('Content-Type: image/png');
imagepng($output);
imagedestroy($output);
?>
以上例程的输出类似于:
Note: 此函数仅在与 GD 库捆绑编译的 PHP 版本中可用。
Padde (2012-12-08 19:29:47)
I played with IMG_FILTER_SMOOTH and tried some negative
values.
-1 to -7: looks like a mix of smoothness and edgedetect
-8: image seems to be completely broken
-9 and lower: kind of sharpening effect (-9 sharper than -10)
I think the sharpening effect in particular could be useful.
martijn(97+1) at gmail dot com (solve math) (2012-10-17 17:34:14)
Simple pixelate function, just in case you are < 5.3
<?php
function pixelate(&$image, $pixelsize){
$maxX = imagesx($image);
$maxY = imagesy($image);
$rad=floor($pixelsize/2);
for($x=$rad;$x<$maxX;$x+=$pixelsize)
for($y=$rad;$y<$maxY;$y+=$pixelsize){
$color = imagecolorat($image, $x, $y);
imagefilledrectangle ($image, $x-$rad, $y-$rad, $x+$pixelsize-1, $y+$pixelsize-1,$color);
}
}
?>
cookie at backbone dot sk (2012-08-23 13:11:24)
a function to create nice vignette effect:
<?php
function vignette($im){
global $width, $height;
$width = imagesx($im);
$height = imagesy($im);
function effect($x, $y, &$rgb){
global $width, $height;
$sharp = 0.4; // 0 - 10 small is sharpnes,
$level = 0.7; // 0 - 1 small is brighter
$l = sin(M_PI / $width * $x) * sin(M_PI / $height * $y);
$l = pow($l, $sharp);
$l = 1 - $level * (1 - $l);
$rgb['red'] *= $l;
$rgb['green'] *= $l;
$rgb['blue'] *= $l;
}
for($x = 0; $x < imagesx($im); ++$x){
for($y = 0; $y < imagesy($im); ++$y){
$index = imagecolorat($im, $x, $y);
$rgb = imagecolorsforindex($im, $index);
effect($x, $y, $rgb);
$color = imagecolorallocate($im, $rgb['red'], $rgb['green'], $rgb['blue']);
imagesetpixel($im, $x, $y, $color);
}
}
return(true);
}
$im = imagecreatefromjpeg('cars7_134.jpg');
if($im and vignette($im)){
header('Content-Type: image/jpeg');
imagejpeg($im);
imagedestroy($im);
}else{
echo 'Vignette failed.';
}
?>
mail at pedrocandeias dot com (2011-10-29 07:20:20)
// With transparent PNG file you can colorize the "positive" items and stand the transparent has it is - Beta code
<?php
header('Content-Type: image/png');
$im = imagecreatefrompng('image.png');
$width = imagesx($im);
$height = imagesy($im);
$imn = imagecreatetruecolor($width, $height);
imagealphablending($imn,false);
$col=imagecolorallocatealpha($imn,255,255,255,127);
imagesavealpha($imn,true);
imagefilledrectangle($imn,0,0,$width,$height,$col);
imagealphablending($imn,true);
imagecopy($imn, $im, 0, 0, 0, 0, $width, $height);
imagefilter($imn, IMG_FILTER_NEGATE);
// FOR A TRANSPARENT PNG FILE WITH SOMETHING INSIDE, YOU CAN CHANGE THE COLOR HERE: I HAVE RGB: 0, 255, 0
imagefilter($imn, IMG_FILTER_COLORIZE, 0, 255, 0);
imagepng($imn);
imagedestroy($imn);
?>
hadrien dot jouet at grownseed dot net (2011-06-21 06:58:48)
For people looking to apply a 'multiply' effect on images like the one in Photoshop (generally b&w ones), you can achieve it with the IMG_FILTER_COLORIZE filter.
<?php
function multiplyColor(&$im, $color = array(255, 0, 0))
{
//get opposite color
$opposite = array(255 - $color[0], 255 - $color[1], 255 - $color[2]);
//now we subtract the opposite color from the image
imagefilter($im, IMG_FILTER_COLORIZE, -$opposite[0], -$opposite[1], -$opposite[2]);
}
?>
bushmakin stas (bushstas at mail dot ru) (2011-03-17 00:26:41)
a function to make all colors gray except the only one
i made it myself so the code is note so beautiful )
<?php
function imagecolorfilter($im){
$height = imagesy($im);
$width = imagesx($im);
for($x=0; $x<$width; $x++){
for($y=0; $y<$height; $y++){
$rgb = ImageColorAt($im, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$c=($r+$g+$b)/3;
//if($g<$r || $g<$b+20){$r=$c;$g=$c; $b=$c;}//leaves only green
//if($b<$r || $b<$g){$r=$c;$g=$c; $b=$c;}//only blue
if($r<$g+30 || $r<$b){$r=$c;$g=$c; $b=$c;}//only red
//if($r<$g-1 || $r>$g+60 || $b>$g-50){$r=$c;$g=$c; $b=$c;}//only yellow
imagesetpixel($im, $x, $y,imagecolorallocate($im, $r,$g,$b));
}
}
}
header ("Content-type: image/jpeg");
$im = imagecreatefromjpeg("image.jpg");
imagecolorfilter($im);
imagejpeg($im);
?>
jonathan dot gotti at gmail dot com (2010-11-30 06:38:06)
IMG_FILTER_COLORIZE doesn't seem to work on palette image, here's a way to achieve same result with palette image:
<?php
//$color is an array containing rvb infos (ie: array(255,80,0))
function paletteColorize($imgResource,array $color){
$nbColors = imagecolorstotal($imgResource);
for($i=0; $i<$nbColors; $i++){
$c = array_values(imagecolorsforindex($imgRes,$i));
for($y=0;$y<3;$y++)
$c[$y] = max(0,min(255,$c[$y]+$color[$y]));
imagecolorset($imgResource,$i,$c[0],$c[1],$c[2]);
}
}
?>
Here's also a function that work on both truecolor and palette images that try to do something similar to greyscale with a given color
<?php
function colorScale($imgRes,array $color){
imagefilter($imgRes,IMG_FILTER_GRAYSCALE);
$color = self::_read_color($color);
$luminance=($color[0]+$color[1]+$color[2])/3; // average luminance added by the color
$brightnessCorrection = $luminance/3; // quantity of brightness to correct for each channel
if( $luminance < 127 ){
$brightnessCorrection -= 127/3; // color is dark so we have to negate the brightness correction
}
if(! imageistruecolor($imgRes) ){
$nbColors = imagecolorstotal($imgRes);
for($i=0; $i<$nbColors; $i++){
$c = array_values(imgagecolorsforindex($imgRes,$i));
for($y=0;$y<3;$y++){
$c[$y] = max(0, min(255, $c[$y] + ($color[$y]-$luminance) + $brightnessCorrection) ); // parentheses just for better comprehension
}
imagecolorset($omgRes,$i,$c[0],$c[1],$c[2]);
}
}else{ // much easier with truecolor
imagefilter($imgRes, IMG_FILTER_COLORIZE, $color[0]-$luminance, $color[1]-$luminance, $color[2]-$luminance);
imagefilter($imgRes, IMG_FILTER_BRIGHTNESS, $brightnessCorrection);
}
}
?>
with hope that someone will find this useful
mail at kavisiegel dot com (2009-06-25 11:11:21)
Searching for a way to easily change the color of the image, I tried IMG_FILTER_COLORIZE. I was unable to get the quality results I wanted. It turns out PHP's Colorize is the equivalent of Photoshop's "Linear Dodge" layer filter.
Hue adjustments have always worked well for me, so I figured I could try with PHP.
This function is kind of slow on larger images, but on small images like what I'm using it for, the difference is trivial.
The script calculates the ratio or red, to green, to blue in the color provided, then scales the image appropriately... unfortunately, it does it pixel by pixel.
Here's a demo and comparison of this function, to photoshop's hue function, to PHP's colorize. http://img146.imageshack.us/img146/3167/imagefilterhuedemo.png
<?php
function imagefilterhue($im,$r,$g,$b){
$rgb = $r+$g+$b;
$col = array($r/$rgb,$b/$rgb,$g/$rgb);
$height = imagesy($im);
$width = imagesx($im);
for($x=0; $x<$width; $x++){
for($y=0; $y<$height; $y++){
$rgb = ImageColorAt($im, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$newR = $r*$col[0] + $g*$col[1] + $b*$col[2];
$newG = $r*$col[2] + $g*$col[0] + $b*$col[1];
$newB = $r*$col[1] + $g*$col[2] + $b*$col[0];
imagesetpixel($im, $x, $y,imagecolorallocate($im, $newR, $newG, $newB));
}
}
}
header ("Content-type: image/jpeg");
$im = imagecreatefromjpeg("test.jpg");
// Usage: Just as imagefilter(), except with no filtertype.
// imagefilterhue(resource $image, int $red, int $green , int $blue)
imagefilterhue($im,2,70,188);
// The equivalent with colorize, as tested in demo image: imagefilter($im, IMG_FILTER_COLORIZE, 2, 70, 188);
imagejpeg($im);
?>
aiden dot mail at freemail dot hu (2008-03-29 12:16:43)
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 );
?>
Kae Cyphet (2007-12-02 16:23:32)
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 (2007-11-21 08:11:45)
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 (2007-11-13 00:31:13)
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 (2007-08-26 09:52:35)
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 (2007-05-08 00:56:40)
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 (2007-03-16 09:26:58)
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 (2007-02-14 12:31:38)
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 (2007-01-14 06:55:15)
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 (2006-08-03 14:16:54)
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 (2006-02-27 11:37:34)
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 (2006-01-31 06:53:07)
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 (2005-12-20 12:48:10)
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 (2004-09-04 13:36:16)
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 (2004-07-20 18:26:03)
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.