imagecolorsforindex
(PHP 4, PHP 5, PHP 7)
imagecolorsforindex — Получение цветов, соответствующих индексу
Описание
Получение цветов, соответствующих заданному индексу.
Список параметров
Ресурс изображения, полученный одной из функций создания изображений, например, такой как imagecreatetruecolor() .
Возвращаемые значения
Возвращает ассоциативный массив с красным, зеленым, синим и альфа ключами, содержащий соответствующие значения для заданного индекса цвета.
Примеры
Пример #1 Пример использования imagecolorsforindex()
// открываем изображение
$im = imagecreatefrompng ( ‘nexen.png’ );
// получаем цвет
$start_x = 40 ;
$start_y = 50 ;
$color_index = imagecolorat ( $im , $start_x , $start_y );
// делаем его удобочитаемым
$color_tran = imagecolorsforindex ( $im , $color_index );
// что это ?
print_r ( $color_tran );
Результатом выполнения данного примера будет что-то подобное:
Смотрите также
- imagecolorat() — Получение индекса цвета пиксела
- imagecolorexact() — Получение индекса заданного цвета
imagecolorsforindex
imagecolorsforindex — Get the colors for an index
Описание
Gets the color for a specified index.
Список параметров
Ресурс изображения, полученный одной из функций создания изображений, например, такой как imagecreatetruecolor() .
The color index.
Возвращаемые значения
Returns an associative array with red, green, blue and alpha keys that contain the appropriate values for the specified color index.
Примеры
Пример #1 imagecolorsforindex() example
// open an image
$im = imagecreatefrompng ( ‘nexen.png’ );
// get a color
$start_x = 40 ;
$start_y = 50 ;
$color_index = imagecolorat ( $im , $start_x , $start_y );
// make it human readable
$color_tran = imagecolorsforindex ( $im , $color_index );
// what is it ?
print_r ( $color_tran );
Результатом выполнения данного примера будет что-то подобное:
Смотрите также
- imagecolorat() — Get the index of the color of a pixel
- imagecolorexact() — Get the index of the specified color
imagecolorsforindex
imagecolorsforindex — Получение цветов, соответствующих индексу
Описание
Получение цветов, соответствующих заданному индексу.
Список параметров
Ресурс изображения, полученный одной из функций создания изображений, например, такой как imagecreatetruecolor() .
Возвращаемые значения
Возвращает ассоциативный массив с красным, зеленым, синим и альфа ключами, содержащий соответствующие значения для заданного индекса цвета.
Примеры
Пример #1 Пример использования imagecolorsforindex()
// открываем изображение
$im = imagecreatefrompng ( ‘nexen.png’ );
// получаем цвет
$start_x = 40 ;
$start_y = 50 ;
$color_index = imagecolorat ( $im , $start_x , $start_y );
// делаем его удобочитаемым
$color_tran = imagecolorsforindex ( $im , $color_index );
// что это ?
print_r ( $color_tran );
Результатом выполнения данного примера будет что-то подобное:
Смотрите также
- imagecolorat() — Получение индекса цвета пиксела
- imagecolorexact() — Получение индекса заданного цвета
Коментарии
here’s a function to greyscale an image even from a truecolor source (jpeg or png).
slightly poor quality, but very fast.
Regarding m4551’s method of conversion — the actual CCIR-approved RGB-to-grayscale conversion is as follows:
grayscale component = 0.2125*R + 0.7154*G + 0.0721*B
(cf. CCIR Recommendation 709 for modern monitors)
To correct m4551 at abasoft dot it example:
might give less colors than $t, so the for loop should call «$i
this is a sepia filter using microsoft’s definition
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 );
>
>
If you would like to change the intensity or lightness level of a specific color, you will need to convert the color format from RGB to HSL.
following function convert RGB array(red,green,blue) to HSL array(hue, saturation, lightness)
/**
* Convert RGB colors array into HSL array
*
* @param array $ RGB colors set
* @return array HSL set
*/
function rgb2hsl ( $rgb )<
$clrR = ( $rgb [ 0 ] / 255 );
$clrG = ( $rgb [ 1 ] / 255 );
$clrB = ( $rgb [ 2 ] / 255 );
$clrMin = min ( $clrR , $clrG , $clrB );
$clrMax = max ( $clrR , $clrG , $clrB );
$deltaMax = $clrMax — $clrMin ;
$L = ( $clrMax + $clrMin ) / 2 ;
if ( 0 == $deltaMax ) <
$H = 0 ;
$S = 0 ;
>
else <
if ( 0.5 > $L ) <
$S = $deltaMax / ( $clrMax + $clrMin );
>
else <
$S = $deltaMax / ( 2 — $clrMax — $clrMin );
>
$deltaR = ((( $clrMax — $clrR ) / 6 ) + ( $deltaMax / 2 )) / $deltaMax ;
$deltaG = ((( $clrMax — $clrG ) / 6 ) + ( $deltaMax / 2 )) / $deltaMax ;
$deltaB = ((( $clrMax — $clrB ) / 6 ) + ( $deltaMax / 2 )) / $deltaMax ;
if ( $clrR == $clrMax ) <
$H = $deltaB — $deltaG ;
>
else if ( $clrG == $clrMax ) <
$H = ( 1 / 3 ) + $deltaR — $deltaB ;
>
else if ( $clrB == $clrMax ) <
$H = ( 2 / 3 ) + $deltaG — $deltaR ;
>
if ( 0 > $H ) $H += 1 ;
if ( 1 $H ) $H -= 1 ;
>
return array( $H , $S , $L );
>
?>
Here’s a better grayscale, sepia, and general tinting function. This function is better because:
1) Works with true color images (the other sepia code didn’t).
2) Provides a more gooder grayscale conversion (yes, I said «more gooder»). The other grayscale code used imagetruecolortopalette, which just doesn’t work well for grayscale conversion.
3) The other sepia code was really colorful, a little too much for my taste. This function allows you to optionally set the tinting of the grayscale to anything you wish.
4) Single function for grayscale, sepia, and any other tinting you can dream up.
Here’s some examples:
imagegrayscaletint ($img); // Grayscale, no tinting
imagegrayscaletint ($img,304,242,209); // What I use for sepia
imagegrayscaletint ($img,0,0,255); // A berry blue image
The RGB values for tinting are normally from 0 to 255. But, you can use values larger than 255 to lighten and «burn» the image. The sepia example above does this a little, the below example provides a better example of lightening the image and burning the light areas out a little:
imagegrayscaletint ($img,400,400,400); // Lighten image
imagegrayscaletint ($img,127,127,127); // Darken image
function imagegrayscaletint (& $img , $tint_r = 255 , $tint_g = 255 , $tint_b = 255 ) <
$width = imagesx ( $img ); $height = imagesy ( $img );
$dest = imagecreate ( $width , $height );
for ( $i = 0 ; $i 256 ; $i ++) imagecolorallocate ( $dest , $i , $i , $i );
imagecopyresized ( $dest , $img , 0 , 0 , 0 , 0 , $width , $height , $width , $height );
for ( $i = 0 ; $i 256 ; $i ++) imagecolorset ( $dest , $i , min ( $i * abs ( $tint_r ) / 255 , 255 ), min ( $i * abs ( $tint_g ) / 255 , 255 ), min ( $i * abs ( $tint_b ) / 255 , 255 ));
$img = imagecreate ( $width , $height );
imagecopy ( $img , $dest , 0 , 0 , 0 , 0 , $width , $height );
imagedestroy ( $dest );
>
?>
While it’s quite easy and intuitive to get the alpha transparency of a pixel with:
= imagecolorsforindex ( $image , imagecolorat ( $image , $x , $y ));
$alpha = $rgba [ «alpha» ];
?>
you should use the return value of the command imagecolorat to get the alpha transparency with the code below because it’s much faster and will have a major impact if you process every pixel of an image:
= imagecolorat ( $image , $x , $y );
$alpha = ( $rgba & 0x7F000000 ) >> 24 ;
?>
The earlier microsoft sepia example seemed to have a factor in which made it pinky. here is a modified example which uses just the Microsoft sepia (as per the wiki sepia entry)
function imagetosepia (& $img ) <
if (!( $t = imagecolorstotal ( $img ))) <
$t = 256 ;
imagetruecolortopalette ( $img , true , $t );
>
$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 );
$green = ( $index [ «red» ] * 0.349 + $index [ «green» ] * 0.686 + $index [ «blue» ] * 0.168 );
$blue = ( $index [ «red» ] * 0.272 + $index [ «green» ] * 0.534 + $index [ «blue» ] * 0.131 );
if ( $red > 255 ) < $red = 255 ; >
if ( $green > 255 ) < $green = 255 ; >
if ( $blue > 255 ) < $blue = 255 ; >
imagecolorset ( $img , $i , $red , $green , $blue );
>
>
?>
= imagecolorat ( $image , $x , $y );
$r = ( $rgba >> 16 ) & 0xFF ;
$g = ( $rgba >> 8 ) & 0xFF ;
$b = $rgba & 0xFF ;
$a = ( $rgba & 0x7F000000 ) >> 24 ;
?>
will only work for truecolor images. With eg GIF images, this will have strange results. For GIF images, you should always use imagecolorsforindex().
I have optimized the rgb2hsl function from slepichev a bit, so that it is a bit shorter and hopefully a bit faster:
/**
* Convert RGB colors array into HSL array
*
* @param array $ RGB colors set, each color component with range 0 to 255
* @return array HSL set, each color component with range 0 to 1
*/
function rgb2hsl ( $rgb ) <
$clrR = ( $rgb [ 0 ]);
$clrG = ( $rgb [ 1 ]);
$clrB = ( $rgb [ 2 ]);
$clrMin = min ( $clrR , $clrG , $clrB );
$clrMax = max ( $clrR , $clrG , $clrB );
$deltaMax = $clrMax — $clrMin ;
$L = ( $clrMax + $clrMin ) / 510 ;
if ( 0 == $deltaMax ) <
$H = 0 ;
$S = 0 ;
>
else <
if ( 0.5 > $L ) <
$S = $deltaMax / ( $clrMax + $clrMin );
>
else <
$S = $deltaMax / ( 510 — $clrMax — $clrMin );
>
if ( $clrMax == $clrR ) <
$H = ( $clrG — $clrB ) / ( 6.0 * $deltaMax );
>
else if ( $clrMax == $clrG ) <
$H = 1 / 3 + ( $clrB — $clrR ) / ( 6.0 * $deltaMax );
>
else <
$H = 2 / 3 + ( $clrR — $clrG ) / ( 6.0 * $deltaMax );
>
if ( 0 > $H ) $H += 1 ;
if ( 1 $H ) $H -= 1 ;
>
return array( $H , $S , $L );
>
?>
Что может вызвать «индекс цвета из диапазона» ошибки для imagecolorsforindex ()?
November 2020
3k раз
При выполнении заплаты размера на большой пучок JPG, PNG и GIF файлы, PHP падает замертво совершенно неожиданно со следующим сообщением об ошибке:
imagecolorsforindex () [function.imagecolorsforindex]: индекс цвета 226 из диапазона
Соответствующий фрагмент кода:
Как может индекс цвета не существует , если уже был возвращен imagecolortransparent ?
1 ответы
Похоже , индекс возвращаемый imagecolortransparent($img) больше , чем размер поддона изображения в вопросе.
Индекс цвета прозрачности является свойством изображения, а не свойство поддона, так что возможно , что изображение может быть создано с помощью этого индекса , установленного за пределами размера поддона, но я хотел бы надеяться , что PHP обнаружил бы это и вернулся -1 из imagecolortransparent() в этой ситуации.
Вы можете проверить , если это то , что происходит путем добавления вызова imagecolorstotal к коду:
проблема
New_Chaynik
New_Chaynik
В принципе всё работает..
Если бы не одно большое НО.
Условие задания такое, что мне нужно прочитать содержимое bmp-файла «как положено», т.е. открыть файл и, считывая побайтно, попиксельно выводить на экран изображение..
Только все графические функции в PHP работают с тройками RGB. А в BMP-файле информация по цветам хранится в каждом байте в виде индексированных значений от 0 до 255, где каждое число — это свой цвет.. Сначала вопрос стоял о конвертации «индексированное значение -> RGB-тройка».. Потом я нашёл вот такую функцию:
array imagecolorsforindex ( resource image, int index); — Возвращает ассоциативный массив с ключами red, green и blue, содержащими соответствующие значения для специфицированного индекса цвета.
Всё бы хорошо, но я столкнулся с следующей тупкой:
Что такое код imagecolorsforindex
(PHP 3, PHP 4, PHP 5)
imagecolorsforindex — Get the colors for an index
Description array imagecolorsforindex ( resource image, int index )
Gets the color for a specified index.
Parameters
An image resource, returned by one of the image creation functions, such as imagecreatetruecolor() .
Return Values
Returns an associative array with red, green, blue and alpha keys that contain the appropriate values for the specified color index.
Examples
Example 1. imagecolorsforindex() example
// get a color
$start_x = 40 ;
$start_y = 50 ;
$color_index = imagecolorat ( $im , $start_x , $start_y );
// make it human readable
$color_tran = imagecolorsforindex ( $im , $color_index );
// what is it ?
print_r ( $color_tran );
The above example will output something similar to:
Array ( [red] => 226 [green] => 222 [blue] => 252 [alpha] => 0 )
Что такое код imagecolorsforindex
(PHP 3, PHP 4, PHP 5)
imagecolorsforindex — Get the colors for an index
Description array imagecolorsforindex ( resource image, int index )
This returns an associative array with red, green, blue and alpha keys that contain the appropriate values for the specified color index.
Пример 1. imagecolorsforindex() example
// get a color
$start_x = 40 ;
$start_y = 50 ;
$color_index = imagecolorat ( $im , $start_x , $start_y );
// make it human readable
$color_tran = imagecolorsforindex ( $im , $color_index );
// what is it ?
echo » ;
This example will output :
Array ( [red] => 226 [green] => 222 [blue] => 252 [alpha] => 0 )
Пред. | Начало | След. |
imagecolorset | Уровень выше | imagecolorstotal |
Если Вы не нашли что искали, то рекомендую воспользоваться поиском по сайту:
FPublisher
Web-технологии: База знаний
Документация PHP
Последние поступления:
ТехЗадание на Землю
Размещена 14 марта 2020 года
Пpоект Genesis (из коpпоpативной пеpеписки)
Шпаргалка по работе с Vim
Размещена 05 декабря 2020 года
Vim довольно мощный редактор, но работа с ним не всегда наглядна.
Например если нужно отредактировать какой-то файл например при помощи crontab, без знания специфики работы с viv никак.
Ошибка: Error: Cannot find a val >Размещена 13 сентабря 2020 года
Если возникает ошибка на centos 5 вида
YumRepo Error: All mirror URLs are not using ftp, http[s] or file.
Eg. Invalid release/
Linux Optimization
Размещена 30 июля 2012 года
Linux.yaroslavl.ru
| |||||||||
imagecolorsforindex — получает цвет для индекса. Описаниеarray imagecolorsforindex (resource image, int index) Возвращает ассоциативный массив с ключами red, green и blue, содержащими соответствующие значения для специфицированного индекса цвета. Что может вызвать ошибку «индекс цвета вне диапазона» для imagecolorsforindex()?При выполнении заплаты размера на большой пучок JPG, PNG и GIF файлы, PHP падает замертво совершенно неожиданно со следующим сообщением об ошибке:
Соответствующий фрагмент кода: Как может индекс цвета не существует, если уже был возвращен imagecolortransparent ? Создан 06 окт. 10 2010-10-06 16:04:53 Saul 1 ответПохоже, что индекс, возвращаемый imagecolortransparent($img) , больше размера поддона для изображения. Индекс цвета прозрачности является свойством изображения, а не свойством поддона, поэтому возможно, что изображение может быть создано с этим индексом, установленным вне размера поддона, но я бы надеялся, что PHP было бы обнаружено это и возвращено -1 от imagecolortransparent() в этой ситуации. Вы можете проверить, если это то, что происходит путем добавления вызова imagecolorstotal к коду: Создан 09 окт. 10 2010-10-09 21:50:58 Gus или . imagecolorsforindex ($ IMG, imagecolorstotal ($ Img) — 1); – Johny 22 янв. 18 2020-01-22 15:15:27 |