Библиотека для инвертирования hex-кодов цвета на php

<?php
/**
 * Inverses a provided hex color. If you pass a hex string with a 
 * hash(#), the function will return a string with a hash prepended
 * @param string $color Hex color to flip
 * @return string Reversed hex color
 * @author Koncept
 * 
 * Last Update: 2008-10-05
 */
function inverseHex( $color )
{
 $color       = trim($color);
 $prependHash = FALSE;

 if(strpos($color,'#')!==FALSE) {
 $prependHash = TRUE;
 $color       = str_replace('#',NULL,$color);
 }

 switch($len=strlen($color)) {
 case 3:
 $color=preg_replace("/(.)(.)(.)/","\\1\\1\\2\\2\\3\\3",$color);
 break;
 case 6:
 break;
 default:
 trigger_error("Invalid hex length ($len). Must be a minimum length of (3) or maxium of (6) characters", E_USER_ERROR);
 }

 if(!preg_match('/^[a-f0-9]{6}$/i',$color)) {
 $color = htmlentities($color);
 trigger_error( "Invalid hex string #$color", E_USER_ERROR );
 }

 $r = dechex(255-hexdec(substr($color,0,2)));
 $r = (strlen($r)>1)?$r:'0'.$r;
 $g = dechex(255-hexdec(substr($color,2,2)));
 $g = (strlen($g)>1)?$g:'0'.$g;
 $b = dechex(255-hexdec(substr($color,4,2)));
 $b = (strlen($b)>1)?$b:'0'.$b;

 return ($prependHash?'#':NULL).$r.$g.$b;
}

// Demo
echo inverseHex('#000000'); // #ffffff
?>
5.00 avg. rating (90% score) - 1 vote

4 комментария

  • […] несколько интересных приемчиков. Первый – это инвертирование цветов. Можно конечно сначала составить массив с цветами и […]

  • Спасибо вам!

  • str_pad(dechex(0xffffff — hexdec(str_replace(‘#’, », ‘#000000’) ) ) , 6, «0», STR_PAD_LEFT);

  • лохопетская функция

    echo «#».str_pad(dechex(0xffffff — 0xff0000), 6, «0», STR_PAD_LEFT);

css.php