Цвет фона всего php

Установить цвет фона в PHP?

Вы должны использовать CSS. Невозможно сделать с PHP.

Я бы проголосовал за вас, поскольку в этой ситуации определенно лучше использовать CSS, но я не очень люблю фразу Невозможно. Подводя итог для ion, просто используйте CSS; PHP — неправильный инструмент для этого, если только у вас нет конкретного случая, когда он незаменим, например. вы должны прочитать цвета из базы данных.

CSS поддерживает ввод текста для цветов (т.е. «черный» = #000000 «белый» = #ffffff). Поэтому я думаю, что полезное решение, которое мы ищем здесь, заключается в том, как заставить PHP получать вывод из текстового поля ввода HTML-формы и иметь он указывает CSS использовать эту строку текста для цвета фона.

Таким образом, когда пользователь вводит «синий» в текстовое поле «какой ваш любимый цвет», ему возвращается страница с синим фоном или любым другим цветом, который он вводит, если он распознается CSS.

Я считаю, что Дэн находится на правильном пути, но, возможно, ему придется уточнить для использования новичками PHP, когда я пытаюсь это сделать, я возвращаю зеленый экран независимо от того, что набирается (я даже установил это как elseif для отображения белого фона, если в текстовое поле не вводятся данные, все еще зеленое?

Вы можете использовать php в таблице стилей. Просто не забудьте установить заголовок («Content-type: text/css») в файле style.php (или как там его зовут)

Это действительно зависит от того, что вам нужно сделать. Если вы хотите установить цвет фона на странице, вам нужно использовать CSS в соответствии с ответами Джея и Дэвида Дорварда.

Источник

imagecolorallocate

Возвращает идентификатор цвета в соответствии с заданными RGB компонентами.

imagecolorallocate() должна вызываться для создания каждого цвета, который будет использоваться в изображении image .

Замечание:

Первый вызов imagecolorallocate() задаёт цвет фона в палитровых изображениях — изображениях, созданных функцией imagecreate() .

Список параметров

Объект GdImage , возвращаемый одной из функций создания изображений, например, такой как imagecreatetruecolor() .

Значение красного компонента цвета.

Значение зелёного компонента цвета.

Значение синего компонента цвета.

Эти аргументы могут принимать либо целочисленные значение в диапазоне от 0 до 255, либо шестнадцатеричные в диапазоне от 0x00 до 0xFF.

Возвращаемые значения

Идентификатор цвета, либо false в случае возникновения ошибки.

Эта функция может возвращать как логическое значение false , так и значение не типа boolean, которое приводится к false . За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.

Список изменений

Версия Описание
8.0.0 image теперь ожидает экземпляр GdImage ; ранее ожидался корректный gd ресурс ( resource ).

Примеры

Пример #1 Пример использования imagecolorallocate()

$im = imagecreate ( 100 , 100 );

// делаем фон красным
$background = imagecolorallocate ( $im , 255 , 0 , 0 );

// создадим несколько цветов
$white = imagecolorallocate ( $im , 255 , 255 , 255 );
$black = imagecolorallocate ( $im , 0 , 0 , 0 );

// шестнадцатеричный способ
$white = imagecolorallocate ( $im , 0xFF , 0xFF , 0xFF );
$black = imagecolorallocate ( $im , 0x00 , 0x00 , 0x00 );

Смотрите также

  • imagecolorallocatealpha() — Создание цвета для изображения
  • imagecolordeallocate() — Разрыв ассоциации переменной с цветом для заданного изображения
Читайте также:  Nginx return php file

User Contributed Notes 21 notes

Note that you can only assign 255 colors to any image palette. If you try assigning more, imagecolorallocate() will fail.

If, for example, you are randomly allocating colors, it will be wise to check if you have used up all of the colors possible. You can use imagecolorclosest() to get the closest assigned color:
//assign random rgb values
$c1 = mt_rand ( 50 , 200 ); //r(ed)
$c2 = mt_rand ( 50 , 200 ); //g(reen)
$c3 = mt_rand ( 50 , 200 ); //b(lue)
//test if we have used up palette
if( imagecolorstotal ( $pic )>= 255 ) //palette used up; pick closest assigned color
$color = imagecolorclosest ( $pic , $c1 , $c2 , $c3 );
> else //palette NOT used up; assign new color
$color = imagecolorallocate ( $pic , $c1 , $c2 , $c3 );
>
?>

Also, imagecolorallocate() will assign a new color EVERY time the function is called, even if the color already exists in the palette:
// [. ]
imagecolorallocate ( $pic , 125 , 125 , 125 ); //returns 5
imagecolorallocate ( $pic , 125 , 125 , 125 ); //returns 6
imagecolorallocate ( $pic , 125 , 125 , 125 ); //returns 7
// [. ]
imagecolorallocate ( $pic , 125 , 125 , 125 ); //returns 23
imagecolorallocate ( $pic , 125 , 125 , 125 ); //returns 25
// [. ]
// etc.
?>

So here, imagecolorexact() is useful:
//see if color already exists
$color = imagecolorexact ( $pic , $c1 , $c2 , $c3 );
if( $color ==- 1 ) //color does not exist; allocate a new one
$color = imagecolorallocate ( $pic , $c1 , $c2 , $c3 );
>
?>

And, for nerdy-ness sake, we can put the two ideas together:
//assign random rgb values
$c1 = mt_rand ( 50 , 200 ); //r(ed)
$c2 = mt_rand ( 50 , 200 ); //g(reen)
$c3 = mt_rand ( 50 , 200 ); //b(lue)
//get color from palette
$color = imagecolorexact ( $pic , $c1 , $c2 , $c3 );
if( $color ==- 1 ) //color does not exist.
//test if we have used up palette
if( imagecolorstotal ( $pic )>= 255 ) //palette used up; pick closest assigned color
$color = imagecolorclosest ( $pic , $c1 , $c2 , $c3 );
> else //palette NOT used up; assign new color
$color = imagecolorallocate ( $pic , $c1 , $c2 , $c3 );
>
>
?>

Or as a function:
function createcolor ( $pic , $c1 , $c2 , $c3 ) //get color from palette
$color = imagecolorexact ( $pic , $c1 , $c2 , $c3 );
if( $color ==- 1 ) //color does not exist.
//test if we have used up palette
if( imagecolorstotal ( $pic )>= 255 ) //palette used up; pick closest assigned color
$color = imagecolorclosest ( $pic , $c1 , $c2 , $c3 );
> else //palette NOT used up; assign new color
$color = imagecolorallocate ( $pic , $c1 , $c2 , $c3 );
>
>
return $color ;
>

for( $i = 0 ; $i < 1000 ; $i ++) < //1000 because it is significantly greater than 255
//assign random rgb values
$c1 = mt_rand ( 50 , 200 ); //r(ed)
$c2 = mt_rand ( 50 , 200 ); //g(reen)
$c3 = mt_rand ( 50 , 200 ); //b(lue)
//generate the color
$color = createcolor ( $pic , $c1 , $c2 , $c3 );
//do something with color.
>
?>

When working on an existant GIF images, if the number of different colours has reached the limits of the GIF format, imagecolorallocate will not use to the colour you ask her within the parameters, she will apply black !

Читайте также:  Посчитать процент от числа java

That’s a problem when generating images «on-the-fly» with many manipulations, from a GIF image.
To go round the problem, you have to convert the GIF image into a PNG one, and then you can work on the PNG and everything will be ok.

For example :
// first, convert into a PNG image
$handle = imagecreatefromgif ( ‘my_image.gif’ );
imagepng ( $handle , ‘my_image.png’ );
imagedestroy ( $handle );

// then, you can work on it
$handle = imagecreatefrompng ( ‘my_image.png’ );
/*
* work on the image
*/
imagegif ( $handle );
?>

this might help someone, how to allocate an color from an html color-definition:

$red = 100 ;
$green = 100 ;
$blue = 100 ;
if( eregi ( «[#]?([0-9a-f])([0-9a-f])([0-9a-f])» , $fg , $ret ) )
<
$red = hexdec ( $ret [ 1 ] );
$green = hexdec ( $ret [ 2 ] );
$blue = hexdec ( $ret [ 3 ] );
>

$text_color = ImageColorAllocate ( $img1 , $red , $green , $blue );
?>

Lots of hsv2rgb commentary but no working example, so here’s mine:

function hsv2rgb ( $h , $s , $v )
$s /= 256.0 ;
if ( $s == 0.0 ) return array( $v , $v , $v );
$h /= ( 256.0 / 6.0 );
$i = floor ( $h );
$f = $h — $i ;
$p = (integer)( $v * ( 1.0 — $s ));
$q = (integer)( $v * ( 1.0 — $s * $f ));
$t = (integer)( $v * ( 1.0 — $s * ( 1.0 — $f )));
switch( $i ) case 0 : return array( $v , $t , $p );
case 1 : return array( $q , $v , $p );
case 2 : return array( $p , $v , $t );
case 3 : return array( $p , $q , $v );
case 4 : return array( $t , $p , $v );
default: return array( $v , $p , $q );
>
>

$image = ImageCreateTrueColor ( 256 , 128 );
for ( $y = 0 ; $y < 64 ; $y ++) for( $x = 0 ; $x < 256 ; $x ++)list( $r , $g , $b ) = hsv2rgb ( $x | 7 , 255 ,( $y * 4 ) | 7 );
$color = ( $r imagesetpixel ( $image , $x , $y — 4 , $color );
>
for ( $y = 64 ; $y < 128 ; $y ++) for( $x = 0 ; $x < 256 ; $x ++)list( $r , $g , $b ) = hsv2rgb ( $x | 7 ,(( 127 - $y )* 4 )| 7 , 255 );
$color = ( $r imagesetpixel ( $image , $x , $y — 4 , $color );
>
for ( $y = 120 ; $y < 128 ; $y ++) for( $x = 0 ; $x < 256 ; $x ++)$color = (( $x | 7 ) imagesetpixel ( $image , $x , $y , $color );
>
header ( «Content-Type: image/png» );
imagepng ( $image );
?>

This works! A Black-Image with vertical centered white Aliased Arial-Text and same left and right margin — used for Menu-Buttons.

function createImgText ( $string = «» , $fontsize = 0 , $marginX = 0 , $imgH = 0 , $fontfile = «» , $imgColorHex = «» , $txtColorHex = «» ) if( $string != «» ) Header ( «Content-type: image/png» );
//
$spacing = 0 ;
$line = array( «linespacing» => $spacing );
$box = @ imageftbbox ( $fontsize , 0 , $fontfile , $string , $line )
or die( «ERROR» );
$tw = $box [ 4 ]- $box [ 0 ]; //image width
$marginY = $imgH — (( $imgH — $fontsize ) / 2 );
$imgWidth = $tw + ( 2 * $marginX );
$im = ImageCreate ( $imgWidth , $imgH );
$int = hexdec ( $imgColorHex );
$arr = array( «red» => 0xFF & ( $int >> 0x10 ),
«green» => 0xFF & ( $int >> 0x8 ),
«blue» => 0xFF & $int );
$black = ImageColorAllocate ( $im , $arr [ «red» ], $arr [ «green» ], $arr [ «blue» ]);
$int = hexdec ( $txtColorHex );
$arr = array( «red» => 0xFF & ( $int >> 0x10 ),
«green» => 0xFF & ( $int >> 0x8 ),
«blue» => 0xFF & $int );
$white = ImageColorAllocate ( $im , $arr [ «red» ], $arr [ «green» ], $arr [ «blue» ]);
ImageFtText ( $im , $fontsize , 0 , $marginX , $marginY , $white , $fontfile , $string , array());
ImagePng ( $im );
ImageDestroy ( $im );
>else echo «ERROR!» ;
>
>
createImgText ( «Hello World» , 9 , 10 , 18 , «arial.ttf» , «000000» , «FFFFFF» );
?>

Читайте также:  Target class in html

Another solution to color limitation issues when creating gradients. This file takes width (px) and left and right colors (hex) and makes a gradient while only allocating 250 colors.

$leftR = hexdec ( substr ( $_GET [ «left» ], 0 , 2 ));
$leftG = hexdec ( substr ( $_GET [ «left» ], 2 , 2 ));
$leftB = hexdec ( substr ( $_GET [ «left» ], 4 , 2 ));
$rightR = hexdec ( substr ( $_GET [ «right» ], 0 , 2 ));
$rightG = hexdec ( substr ( $_GET [ «right» ], 2 , 2 ));
$rightB = hexdec ( substr ( $_GET [ «right» ], 4 , 2 ));
$image = imagecreate ( $_GET [ «width» ], 1 );
for( $i = 0 ; $i < 250 ; $i ++) $colorset [ $i ] = imagecolorallocate ( $image , $leftR + ( $i *(( $rightR - $leftR )/ 250 )), $leftG + ( $i *(( $rightG - $leftG )/ 250 )), $leftB + ( $i *(( $rightB - $leftB )/ 250 )));
>
for( $i = 0 ; $i <( $_GET [ "width" ]); $i ++) imagesetpixel ( $image , $i , 0 , $colorset [(int)( $i /( $_GET [ "width" ]/ 250 ))] );
>
header ( «Content-type: image/png» );
imagepng ( $image );
imagedestroy ( $image );
?>

example: gradient.php?width=640&left=000000&right=FF0000

Makes a 640px-wide image that fades from black to red.

Actually, you can’t allocate more than 256 colours for an paletted image (ImageCreate).
Use ImageCreateTrueColor instead. For it to work, you need libgd version 2 support in php though.

Also, when you need more then 256 colors, use imagecreatetruecolor function. With this function you can use unlimited number of colors.

If you even in a situation where it’s not allocating the color you want it could be because of your images color allocation table. GIF and 8-bit PNG images are very susceptible to this.

If your using an GIF and PNG try dropping a color from the table, should let you allocate another.

Another more general variation on the theme using the same naming conventions as the hexdec and dechex built-in functions .

array hexrgb ( string hex_string )

An associative array of the RGB components specified in hex_string.

$rgb = hexrgb ( «0xAABBCC» );
print_r ( $rgb );
?>

Output is:

function hexrgb ( $hexstr )
$int = hexdec ( $hexstr );

return array( «red» => 0xFF & ( $int >> 0x10 ),
«green» => 0xFF & ( $int >> 0x8 ),
«blue» => 0xFF & $int );
>
?>

The output of hexdec can then be passed to imagecolorallocate and manipulated as required.

This nifty function will produce the negative of a given image!

header ( «Content-type: image/jpeg» );

$source = imagecreatefromjpeg ( $pic ); // Source
$width = imagesx ( $source ); $height = imagesy ( $source );

$im = imagecreatetruecolor ( $width , $height ); // Our negative img in the making

$colors = imagecolorsforindex ( $source , imagecolorat ( $source , $x , $y ));

// this is what makes the colors negative
$r = 255 — $colors [ ‘red’ ];
$g = 255 — $colors [ ‘green’ ];
$b = 255 — $colors [ ‘blue’ ];
$test = imagecolorallocate ( $im , $r , $g , $b );
imagesetpixel ( $im , $x , $y , $test );
>
>

imagejpeg ( $im );
imagedestroy ( $im );
>

Источник

Оцените статью