Hexadecimal renk kodları özellikle web tasarım’da sık sık kullanılmaktadır. Hexadecimal renk kodları 16’lık sayı sistemine göre düzenlenmiş renk kodlarıdır. Hexadecimal renk kodları tarayıcılar tarafından 16’lık sistemden 10’luk sisteme yani RGB(red, green, blue) formatına çevrilerek işlenir.
Hexadecimal renk kodları 6 haneden oluşmaktadır. Örnek vermek gerekirse beyaz rengin hexadecimal karşılığı FFFFFF’dir. Bunu RGB çevirmek istersek ilk iki FF red yani kırmızıyı ikinci FF kısmı green yani yeşili son iki FF’de blue yani maviyi temsil etmektedir.
Hexadecimal #FFFFFF kodunu RGB’ye çevirecek olursak:
R= FF = (15*16)+15 = 255
G= FF = (15*16)+15 = 255
B= FF = (15*16)+15 = 255
rgb(255, 255, 255) sonuçlarını elde etmiş oluruz.
Zaman zaman Php’de de hexadecimal renk kodlarını RGB formatına çevirmemiz gerekebilir. bu gibi durumlar için aşağıdaki fonksiyonu kullanabilirsiniz.
Php Hexadecimal Renk Kodunu RGB Formatına Çevirme Fonksiyonu
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function hex2RGB($hexStr, $returnAsString = false, $seperator = ‘,’) { $hexStr = preg_replace(“/[^0-9A-Fa-f]/”, ”, $hexStr); // Gets a proper hex string $rgbArray = array(); if (strlen($hexStr) == 6) { //If a proper hex code, convert using bitwise operation. No overhead… faster $colorVal = hexdec($hexStr); $rgbArray[‘red’] = 0xFF & ($colorVal >> 0x10); $rgbArray[‘green’] = 0xFF & ($colorVal >> 0x8); $rgbArray[‘blue’] = 0xFF & $colorVal; } elseif (strlen($hexStr) == 3) { //if shorthand notation, need some string manipulations $rgbArray[‘red’] = hexdec(str_repeat(substr($hexStr, 0, 1), 2)); $rgbArray[‘green’] = hexdec(str_repeat(substr($hexStr, 1, 1), 2)); $rgbArray[‘blue’] = hexdec(str_repeat(substr($hexStr, 2, 1), 2)); } else { return false; //Invalid hex color code } return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray; // returns the rgb string or the associative array } |
Kullanımı:
1 2 3 4 5 6 7 8 9 10 | echo var_dump(hex2RGB(“BF8363”)); /* Ekran Çıktısı: array (size=3) ‘red’ => int 191 ‘green’ => int 131 ‘blue’ => int 99 */ echo hex2RGB(“BF8363”)[‘red’]; //Ekran Çıktısı: 191 |