imagecolorset
This sets the specified index in the palette to the specified color. This is useful for creating flood-fill-like effects in palleted images without the overhead of performing the actual flood-fill.
Parameters
A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor() .
Return Values
The function returns null on success, or false on failure.
Changelog
Version | Description |
---|---|
8.0.0 | image expects a GdImage instance now; previously, a valid gd resource was expected. |
Examples
Example #1 imagecolorset() example
// Create a 300×100 image
$im = imagecreate ( 300 , 100 );
?php
// Set the background to be red
imagecolorallocate ( $im , 255 , 0 , 0 );
// Get the color index for the background
$bg = imagecolorat ( $im , 0 , 0 );
// Set the backgrund to be blue
imagecolorset ( $im , $bg , 0 , 0 , 255 );
// Output the image to the browser
header ( ‘Content-Type: image/png’ );
imagepng ( $im );
imagedestroy ( $im );
?>
See Also
User Contributed Notes 10 notes
If you want to convert a Color image to Grayscale without creating a blotchy image, use this color calculation:
function imagetograyscale ( $im )
if ( imageistruecolor ( $im )) imagetruecolortopalette ( $im , false , 256 );
>
for ( $c = 0 ; $c < imagecolorstotal ( $im ); $c ++) $col = imagecolorsforindex ( $im , $c );
$gray = round ( 0.299 * $col [ ‘red’ ] + 0.587 * $col [ ‘green’ ] + 0.114 * $col [ ‘blue’ ]);
imagecolorset ( $im , $c , $gray , $gray , $gray );
>
>
?>
I’ve been looking for a simple function which «colorizes» an image, without any success . it looks like a lot of people mean something different with «colorizing» an image, because actually colorzing means multiplying the old color’s grayscale with the new color. So a white pixel would become 100% of the colorize-to-color and a black pixel would stay black (I know I can’t explain well . I hope you understood, otherwise take a look at the example below the functions’ code).
for ( $x = 0 ; $x < $numColors ; $x ++) list( $r , $g , $b ) = array_values ( imageColorsForIndex ( $img , $x ));
// calculate grayscale in percent
$grayscale = ( $r + $g + $b ) / 3 / 0xff ;
imageColorSet ( $img , $x ,
$grayscale * $rgb [ 0 ],
$grayscale * $rgb [ 1 ],
$grayscale * $rgb [ 2 ]
);
>
return true ;
>
?>
Example of usage:
$color = array( 0xff , 0xaa , 0x2a ); // color to convert to
$url = ‘http://sundog.net/images/uploads/1_google_logo.jpg’ ;
$img = imageCreateFromJpeg ( $url );
image_colorize ( $img , $color );
header ( ‘Content-type: image/gif’ );
imageGif ( $img );
exit;
?>
Enjoy
this is helpful if you would like to implement a color theme system in your website. try it out
Davide Candiloro Italy
function colorize ($pngpath, $r, $g, $b)
/*
REQUIRES: $pngpath to be a valid path of a greyscale PNG-8 image with 64 colors palette
$r, $g, $b to be integers in the range 0..255
EFFECTS: returns the png image colorized with the color represented by $r, $g, $b.
*/
header(«Content-type: image/png»);
$im = imagecreatefrompng(«images/table.png»);
imagetruecolortopalette($im, FALSE, 256);
for ($c = 0; $c < 64; $c++)< /*64 is the number of colors in the PNG-8 palette*/
$col = imagecolorsforindex($im, $c);
imagecolorset ( $im, $c, $r*$col[‘red’]/256, $g*$col[‘green’]/256, $b*$col[‘blue’]/256); /*replaces original greyscale palette with a colorized one*/
>
here’s a function to greyscale an image even from a truecolor source (jpeg or png).
slightly poor quality, but very fast.
function imagegreyscale(&$img, $dither=1) <
if (!($t = imagecolorstotal($img))) $t = 256;
imagetruecolortopalette($img, $dither, $t);
>
for ($c = 0; $c < $t; $c++) <
$col = imagecolorsforindex($img, $c);
$min = min($col[‘red’],$col[‘green’],$col[‘blue’]);
$max = max($col[‘red’],$col[‘green’],$col[‘blue’]);
$i = ($max+$min)/2;
imagecolorset($img, $c, $i, $i, $i);
>
>
If you are creating a palette image from scratch you have to use imagecolorallocate() for each index before you can use imagecolorset() on it.
Here is a function to colorize a picture gradient style.
All you have to do is to pass an img-object and an array of colors.
$arr = array(‘#000000’, ‘#990000’, ‘#00FFFF’, ‘#FFFFDD’);
colorize ($img, $arr);
function colorize ( $imgdata , $palette )
imageTrueColorToPalette ( $imgdata , false , 0xFF );
$l = count ( $palette )- 1 ;
$i = imagecolorstotal ( $imgdata );
while ( $i —)
list( $r , $g , $b ) = array_values ( imageColorsForIndex ( $imgdata , $i ));
$grayscale = ( $r * .3 + $g * .59 + $b * .11 ) / 0xFF ;
$tbase = str_replace ( «#» , » , $palette [ $pos ]);
$baseR = hexdec ( substr ( $tbase , 0 , 2 ));
$baseG = hexdec ( substr ( $tbase , 2 , 2 ));
$baseB = hexdec ( substr ( $tbase , 4 , 2 ));
$tmix = str_replace ( «#» , » , $palette [ $pos + 1 ]);
$mixR = hexdec ( substr ( $tmix , 0 , 2 ));
$mixG = hexdec ( substr ( $tmix , 2 , 2 ));
$mixB = hexdec ( substr ( $tmix , 4 , 2 ));
$resR = $baseR +( $mixR — $baseR )* $perc ;
$resG = $baseG +( $mixG — $baseG )* $perc ;
$resB = $baseB +( $mixB — $baseB )* $perc ;
imagecolorset ( $imgdata , $i , $resR , $resG , $resB );
>
>
?>
This function change colors of an image with ranges 0>100 for each primary color:
int ImageSelectiveColor (int im, int red, int green, int blue)
im is image pointer
red, green and blue are ranges 0->100
function ImageSelectiveColor($im,$red,$green,$blue)
<
for($i=0;$i
$col=ImageColorsForIndex($im,$i);
$red_set=$red/100*$col[‘red’];
$green_set=$green/100*$col[‘green’];
$blue_set=$blue/100*$col[‘blue’];
if($red_set>255)$red_set=255;
if($green_set>255)$green_set=255;
if($blue_set>255)$blue_set=255;
imagecolorset($im,$i,$red_set,$green_set,$blue_set);
I had the same problem as heavyraptor2 so i made this function.
function imagecolorize ( $im , $endcolor ) //funcion takes image and turns black into $endcolor, white to white and
//everything in between in corresponding gradient
//$endcolor should be 6 char html color
//make sure it has usable palette
if ( imageistruecolor ( $im )) imagetruecolortopalette ( $im , false , 256 );
>
//first make it gray to be sure of even results (thanks moxleystratton.com)
//comment this loop if you want the output based on, for example,
//the red channel (for this take a look at the $gray-var in the last loop)
for ( $c = 0 ; $c < imagecolorstotal ( $im ); $c ++) $col = imagecolorsforindex ( $im , $c );
$gray = round ( 0.299 * $col [ ‘red’ ] + 0.587 * $col [ ‘green’ ] + 0.114 * $col [ ‘blue’ ]);
imagecolorset ( $im , $c , $gray , $gray , $gray );
>
//determine end-colors in hexdec
$EndcolorRGB [ ‘r’ ] = hexdec ( substr ( $endcolor , 0 , 2 ));
$EndcolorRGB [ ‘g’ ] = hexdec ( substr ( $endcolor , 2 , 2 ));
$EndcolorRGB [ ‘b’ ] = hexdec ( substr ( $endcolor , 4 , 2 ));
//determine gradient-delta’s
$stepR = ( 255 — $EndcolorRGB [ ‘r’ ])/ 255.0 ;
$stepG = ( 255 — $EndcolorRGB [ ‘g’ ])/ 255.0 ;
$stepB = ( 255 — $EndcolorRGB [ ‘b’ ])/ 255.0 ;
//aColor contains the 256 gradations between endcolor(i=0) and white(i=255)
$aColor = array();
for ( $i = 0 ; $i $aColor [ $i ][ ‘r’ ] = $EndcolorRGB [ ‘r’ ] + ( $i * $stepR );
$aColor [ $i ][ ‘g’ ] = $EndcolorRGB [ ‘g’ ] + ( $i * $stepG );
$aColor [ $i ][ ‘b’ ] = $EndcolorRGB [ ‘b’ ] + ( $i * $stepB );
>
//for every color-index we now replace $gray-values for $aColor
for ( $c = 0 ; $c < imagecolorstotal ( $im ); $c ++)$currentColorRGB = imagecolorsforindex ( $im , $c );
$gray = $currentColorRGB [ ‘red’ ]; //image is grayscale, so red,green and blue
// should be equal. We use this number as key of aColor
imagecolorset ( $im , $c ,(int) $aColor [ $gray ][ ‘r’ ], (int) $aColor [ $gray ][ ‘g’ ], (int) $aColor [ $gray ][ ‘b’ ]);
>
> ?>
Here is a function to turn an image into pure black and white
function imagepurebw ( $img , $amount = 383 ) $total = imagecolorstotal ( $img );
for ( $i = 0 ; $i < $total ; $i ++ ) $index = imagecolorsforindex ( $img , $i );
array_pop ( $index );
$color = ( array_sum ( $index ) > $amount ) ? 255 : 0 ;
imagecolorset ( $img , $i , $color , $color , $color );
>
>
here’s a simple function to greyscale an image.
- GD and Image Functions
- gd_info
- getimagesize
- getimagesizefromstring
- image_type_to_extension
- image_type_to_mime_type
- image2wbmp
- imageaffine
- imageaffinematrixconcat
- imageaffinematrixget
- imagealphablending
- imageantialias
- imagearc
- imageavif
- imagebmp
- imagechar
- imagecharup
- imagecolorallocate
- imagecolorallocatealpha
- imagecolorat
- imagecolorclosest
- imagecolorclosestalpha
- imagecolorclosesthwb
- imagecolordeallocate
- imagecolorexact
- imagecolorexactalpha
- imagecolormatch
- imagecolorresolve
- imagecolorresolvealpha
- imagecolorset
- imagecolorsforindex
- imagecolorstotal
- imagecolortransparent
- imageconvolution
- imagecopy
- imagecopymerge
- imagecopymergegray
- imagecopyresampled
- imagecopyresized
- imagecreate
- imagecreatefromavif
- imagecreatefrombmp
- imagecreatefromgd2
- imagecreatefromgd2part
- imagecreatefromgd
- imagecreatefromgif
- imagecreatefromjpeg
- imagecreatefrompng
- imagecreatefromstring
- imagecreatefromtga
- imagecreatefromwbmp
- imagecreatefromwebp
- imagecreatefromxbm
- imagecreatefromxpm
- imagecreatetruecolor
- imagecrop
- imagecropauto
- imagedashedline
- imagedestroy
- imageellipse
- imagefill
- imagefilledarc
- imagefilledellipse
- imagefilledpolygon
- imagefilledrectangle
- imagefilltoborder
- imagefilter
- imageflip
- imagefontheight
- imagefontwidth
- imageftbbox
- imagefttext
- imagegammacorrect
- imagegd2
- imagegd
- imagegetclip
- imagegetinterpolation
- imagegif
- imagegrabscreen
- imagegrabwindow
- imageinterlace
- imageistruecolor
- imagejpeg
- imagelayereffect
- imageline
- imageloadfont
- imageopenpolygon
- imagepalettecopy
- imagepalettetotruecolor
- imagepng
- imagepolygon
- imagerectangle
- imageresolution
- imagerotate
- imagesavealpha
- imagescale
- imagesetbrush
- imagesetclip
- imagesetinterpolation
- imagesetpixel
- imagesetstyle
- imagesetthickness
- imagesettile
- imagestring
- imagestringup
- imagesx
- imagesy
- imagetruecolortopalette
- imagettfbbox
- imagettftext
- imagetypes
- imagewbmp
- imagewebp
- imagexbm
- iptcembed
- iptcparse
- jpeg2wbmp
- png2wbmp
PHP: генерирование оттенков
Существуют различные способы установки цвета. Два самых популярных значения в Сети являются HEX и RGB. Оба этих значения имеют логическую формулу работы с помощью которой мы можем легко сгенерировать оттенки нужного нам цветового значения.
Самый простой способ получить другой оттенок цвета, чтобы использовать значение RGB, это потому, чем выше значение, тем светлее цвет, а чем меньше значение, тем цвет будет темнее. Так что все, что нам нужно делать — это взять начальное значение цвета, преобразовать его в RGB и удалить или добавить нужный процент.
Чтобы преобразовать цвета в RGB PHP есть функция HexDec() , которую мы используем, чтобы вернуть десятичное значение шестнадцатеричного значения.
Напишем две элементарные функции, которые будет делать нам оттенки.
function hex2rgb($hex) < return array( hexdec(substr($hex,1,2)), hexdec(substr($hex,3,2)), hexdec(substr($hex,5,2)) ); >function different_shade($rgb, $type) < $newShade = array(); $percentageChange = 7.5; if($type == 'lighter') < $newShade = Array( 255-(255-$rgb[0]) + $percentageChange, 255-(255-$rgb[1]) + $percentageChange, 255-(255-$rgb[2]) + $percentageChange ); >else < $newShade = Array( $rgb[0] - $percentageChange, $rgb[1] - $percentageChange, $rgb[2] - $percentageChange ); >return $newShade; >
Используя эти две функции вы сможете получить различные оттенки цвета.
Помните, что значения RGB в диапазоне от 0 до 255 поэтому убедитесь, что ваш новый оттенок в этом диапазоне.