PHP Conference Japan 2024

hexdec

(PHP 4, PHP 5, PHP 7, PHP 8)

hexdec十六進位轉十進位

說明

hexdec(字串 $hex_string): 整數|浮點數

傳回由 hex_string 參數表示的十六進位數字的十進位等值。 hexdec() 將十六進位字串轉換為十進位數字。

hexdec() 會忽略它遇到的任何非十六進位字元。從 PHP 7.4.0 開始,提供任何無效字元已被棄用。

參數

hex_string

要轉換的十六進位字串

傳回值

hex_string 的十進位表示

更新日誌

版本 說明
7.4.0 傳遞無效字元現在會產生棄用通知。結果仍將如同無效字元不存在一樣進行計算。

範例

範例 #1 hexdec() 範例

<?php
var_dump
(hexdec("See"));
var_dump(hexdec("ee"));
// 兩者皆印出 "int(238)"

var_dump(hexdec("that")); // 印出 "int(10)"
var_dump(hexdec("a0")); // 印出 "int(160)"
?>

注意事項

注意:

此函式可以轉換大於平台 int 類型所能容納的數字,在這種情況下,較大的值會以 float 類型返回。

參見

新增註釋

使用者貢獻的註釋 31 則註釋

hafees at msn dot com
14 年前
使用此函式將十六進位顏色碼轉換為其 RGB 等效值。與這裡提供的許多其他函式不同,它可以正確處理十六進位顏色簡寫表示法。

此外,如果給定正確的十六進位顏色值(6 位數),它會使用位元運算來加快結果。

例如:#FFF 和 #FFFFFF 將產生相同的結果

<?php
/**
* Convert a hexa decimal color code to its RGB equivalent
*
* @param string $hexStr (hexadecimal color value)
* @param boolean $returnAsString (if set true, returns the value separated by the separator character. Otherwise returns associative array)
* @param string $seperator (to separate RGB values. Applicable only if second parameter is true.)
* @return array or string (depending on second parameter. Returns False if invalid hex color value)
*/
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
} ?>

輸出

hex2RGB("#FF0") -> array( red =>255, green => 255, blue => 0)
hex2RGB("#FFFF00) -> 與上述相同
hex2RGB("#FF0", true) -> 255,255,0
hex2RGB("#FF0", true, ":") -> 255:255:0
Ultimater at gmail dot com
15 年前
hexdec 不接受小數點後的數字。
如果您有一個像 c20.db18 這樣的數字怎麼辦?
<?php
函數 floatinghexdec($str)
{
list(
$intgr,$hex) = explode('.',$str,2);
$intgr = preg_replace('/[^A-Fa-f0-9]/', "", $intgr);
$hex = preg_replace('/[^A-Fa-f0-9]/', "", $hex);
$answer = 0;
for (
$i = 0; $i < strlen($hex); $i++)
{
$digit = hexdec(substr($hex,$i,1)) / 16; // .f 是 15/16,因為在十進制中 .9 是 9/10
$answer += $digit / pow(16, $i);
}
return
hexdec($intgr) + $answer;
}

echo
floatinghexdec("ff.ff"); //255.99609375
?>
chrism at four dot net
22 年前
從 4.1.0 版開始,hexdec 不再顯示
相同的長度限制,因此
與之前的 PHP 版本相比,在處理大數字時會有不同的結果。

要獲得相同的結果,請使用

(int) hexdec (...)
Gabriel Reguly
19 年前
繼 "rledger at gmail dot com" 的 esnhexdec 之後,esndechex

<?php
函數 esndechex($dec){
$a = strtoupper(dechex(substr($dec, 1, 2)));
$b = strtoupper(dechex(substr($dec, 3, 10)));
return
$a . $b;
}
?>
匿名
17 年前
// 獲取十六進位顏色值並返回 RGB 值的函式
function hexrgb($hexstr, $rgb) {
$int = hexdec($hexstr);
switch($rgb) {
case "r"
return 0xFF & $int >> 0x10;
break;
case "g"
return 0xFF & ($int >> 0x8);
break;
case "b"
return 0xFF & $int;
break;
default
return array(
"r" => 0xFF & $int >> 0x10,
"g" => 0xFF & ($int >> 0x8),
"b" => 0xFF & $int
);
break;
}
)}// 十六進位轉 RGB 結束

//用法
echo hexrgb("1a2b3c", r); // 26
echo hexrgb("1a2b3c", g); // 43
echo hexrgb("1a2b3c", b); // 60
//或

var_dump(hexrgb("1a2b3c", rgb)); //array(3) { ["r"]=> int(26) ["g"]=> int(43) ["b"]=> int(60) }
cory at lavacube dot com
19 年前
一個方便的小函式,用於將十六進位顏色代碼轉換為「網頁安全」顏色...

<?php

function color_mkwebsafe ( $in )
{
// 將值放入易於使用的陣列中
$vals['r'] = hexdec( substr($in, 0, 2) );
$vals['g'] = hexdec( substr($in, 2, 2) );
$vals['b'] = hexdec( substr($in, 4, 2) );

// 迴圈處理
foreach( $vals as $val )
{
// 轉換值
$val = ( round($val/51) * 51 );
// 轉換為十六進位
$out .= str_pad(dechex($val), 2, '0', STR_PAD_LEFT);
}

return
$out;
}

?>

範例:color_mkwebsafe('0e5c94');
產生:006699

希望這對某些人有所幫助... 祝編碼愉快。 :-)
groobo
19 年前
這只是對 marfastic 的 ligten_up 腳本的修改,它只是將 mod_color 加到/減去 orig_color。
我經常使用它來調整色調,而不僅僅是亮度

<?
function mod_color($orig_color, $mod, $mod_color){
/*
$orig_color - 原始 HTML 顏色,十六進位
$mod_color - 修改顏色,十六進位
$mod - 修飾符 '+' 或 '-'
用法:mod_color('CCCCCC', '+', '000033')
*/
// 進行快速驗證
preg_match("/([0-9]|[A-F]){6}/i",$orig_color,$orig_arr);
preg_match("/([0-9]|[A-F]){6}/i",$mod_color,$mod_arr);
if ($orig_arr[0] && $mod_arr[0]) {
for ($i=0; $i<6; $i=$i+2) {
從 $orig_arr[0] 中,自索引 $i 開始擷取長度為 2 的子字串,賦值給 $orig_x。
從 $mod_arr[0] 中,自索引 $i 開始擷取長度為 2 的子字串,賦值給 $mod_x。
如果 $mod 為 '+',則將 $orig_x 和 $mod_x 從十六進位轉換為十進位後相加,結果賦值給 $new_x。
否則,將 $orig_x 和 $mod_x 從十六進位轉換為十進位後相減,結果賦值給 $new_x。
如果 $new_x 小於 0,則將 $new_x 設為 0。
否則,如果 $new_x 大於 255,則將 $new_x 設為 255。
將 $new_x 從十進位轉換為十六進位。
將 $new_x 附加到 $ret 字串後。
}
回傳 $ret。
} 否則,回傳 false。
}
?>
使用者 flurinj at gmx dot net 的留言連結和段落符號。
14 年前
以下是我將十六進位字串轉換為帶符號十進位值的版本

```php
使用者 brian at sagesport dot com 的留言連結和段落符號。
19 年前
我看到的現有十六進位轉十進位轉換程式的問題是缺乏錯誤捕捉。我堅持這樣的理論:在編寫像這樣的通用程式時,應該盡可能涵蓋所有情況。我的背景相當多元,涵蓋了各種設計/開發語言,包含網頁和桌面應用程式。因此,我看過多種編寫十六進位顏色的格式。

例如,紅色可以寫成以下格式
#ff0000
&Hff0000
#ff
&Hff

因此,我編寫了一個函式,它不區分大小寫,並考慮到不同開發人員傾向於以不同方式格式化十六進位顏色的可能性。

<?php
function convert_color($hex){
$len = strlen($hex);
$chars = array("#","&","H","h");
$hex = strip_chars($hex, $chars);
preg_match("/([0-9]|[A-F]|[a-f]){".$len."}/i",$hex,$arr);
$hex = $arr[0];
if (
$hex) {
switch(
$len) {
case
2:
$red = hexdec($hex);
$green = 0;
$blue = 0;
break;
case
4:
$red = hexdec(substr($hex,0,2));
$green=hexdec(substr($hex,2,2));
$blue = 0;
break;
case
6:
$red = hexdec(substr($hex,0,2));
$green=hexdec(substr($hex,2,2));
$blue = hexdec(substr($hex,4,2));
break;
};
$color[success] = true;
$color[r] = $red;
$color[g] = $green;
$color[b] = $blue;
return
$color;
} else {
$color[success] = false;
$color[error] = "unable to convert hex to dec";
};
}

function
strip_chars($string, $char){
$len = strlen($string);
$count = count($char);
if (
$count >= 2) {
for (
$i=0;$i<=$count;$i++) {
if (
$char[$i]) {
$found = stristr($string,$char[$i]);
if (
$found) {
$val = substr($string,$found+1,$len-1);
$string = $val;
};
};
};
} else {
$found = stristr($string,$char);
if (
$found) {
$val = substr($string,$found+1,$len-1);
};
};
echo
$val;
return
$val;
}

/*
To use simply use the following function call:
$color = convert_color("#FF");
this will return the following assoc array if successful:
*[success] = true
*[r] = 255
*[g] = 0
*[b] = 0

or copy and paste the following code:

$hex = "FFFFFF"; // Color White
$color = convert_color($hex);
var_dump($color);
*/
?>

如您所見,「convert_color」函式接受大多數可接受格式的十六進位 # 字元,並返回一個關聯陣列。如果函式成功,[success] 設定為 TRUE,否則設定為 FALSE。陣列成員 [r]、[g] 和 [b] 分別保存紅色、綠色和藍色的值。如果失敗,[error] 會保存自訂錯誤訊息。

「strip_chars」是一個輔助函式,用於從十六進位字串中移除不需要的字元,並將串接後的字串傳回呼叫函式。它可以接受單個值或值的陣列作為要移除的字元。
Halit YEL - halityesil at globya dot net
15 年前
RGB 轉十六進位
十六進位轉 RGB
函式

<?PHP

function rgb2hex2rgb($c){
if(!
$c) return false;
$c = trim($c);
$out = false;
if(
preg_match("/^[0-9ABCDEFabcdef\#]+$/i", $c)){
$c = str_replace('#','', $c);
$l = strlen($c) == 3 ? 1 : (strlen($c) == 6 ? 2 : false);

if(
$l){
unset(
$out);
$out[0] = $out['r'] = $out['red'] = hexdec(substr($c, 0,1*$l));
$out[1] = $out['g'] = $out['green'] = hexdec(substr($c, 1*$l,1*$l));
$out[2] = $out['b'] = $out['blue'] = hexdec(substr($c, 2*$l,1*$l));
}else
$out = false;

}elseif (
preg_match("/^[0-9]+(,| |.)+[0-9]+(,| |.)+[0-9]+$/i", $c)){
$spr = str_replace(array(',',' ','.'), ':', $c);
$e = explode(":", $spr);
if(
count($e) != 3) return false;
$out = '#';
for(
$i = 0; $i<3; $i++)
$e[$i] = dechex(($e[$i] <= 0)?0:(($e[$i] >= 255)?255:$e[$i]));

for(
$i = 0; $i<3; $i++)
$out .= ((strlen($e[$i]) < 2)?'0':'').$e[$i];

$out = strtoupper($out);
}else
$out = false;

return
$out;
}

?>

輸出

#FFFFFF =>
陣列{
red=>255,
green=>255,
blue=>255,
r=>255,
g=>255,
b=>255,
0=>255,
1=>255,
2=>255
}


#FFCCEE =>
陣列{
red=>255,
green=>204,
blue=>238,
r=>255,
g=>204,
b=>238,
0=>255,
1=>204,
2=>238
}
CC22FF =>
陣列{
red=>204,
green=>34,
blue=>255,
r=>204,
g=>34,
b=>255,
0=>204,
1=>34,
2=>255
}

0 65 255 => #0041FF
255.150.3 => #FF9603
100,100,250 => #6464FA


[由 danbrown AT php DOT net 編輯 - 包含 (ajim1417 AT gmail DOT com) 於 2010 年 1 月 27 日的多項錯誤修正:取代 explode() 中的拼寫錯誤,並將 eregi() 呼叫更新為 preg_match()]
sneskid at hotmail dot com
12 年前
如果您想要建立或解析帶正負號的十六進位字串

<?php
// $d 應該是一個整數
function sdechex($d) { return ($d<0) ? ('-' . dechex(-$d)) : dechex($d); }

// $h 應該是一個字串
function shexdec($h) { return ($h[0] === '-') ? -('0x' . substr($h,1) + 0) : ('0x' . $h + 0); }

// 測試
$h = sdechex(-123); // 字串(3) "-7b"
$d = shexdec($h); // 整數(-123)
var_dump($h, $d);
?>

另請注意,('0x' . $hexstr + 0) 比 hexdec() 更快
(在 PHP v5.2.17 上測試)
programacion at mundosica dot com
12 年前
這是另一個將 MAC 位址轉換為十進位的函式

<?php
函式 get_mac_decimal($mac) {
$clear_mac = preg_replace('/[^0-9A-F]/i','',$mac);
$mac_decimal = array();
for (
$i = 0; $i < strlen($clear_mac); $i += 2 ):
$mac_decimal[] = hexdec(substr($clear_mac, $i, 2));
endfor;
return
implode('.',$mac_decimal);
}
?>
匿名
19 年前
我想了很久,將十六進位顏色碼轉換成 RGB 顏色碼的最佳方法是什麼,而我剛剛找到了最簡單的方法!

<?php
$hex
= "FF00FF";
$rgb = hexdec($hex); // 16711935
?>

希望這能節省您的時間! :)
chuckySTAR
15 年前
這是我的 hexdec 函式,使用 BC Math 處理更大的數字

<?php
函式 bchexdec($hex)
{
$len = strlen($hex);
for (
$i = 1; $i <= $len; $i++)
$dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i))));

return
$dec;
}

echo
bchexdec('ffffffffffffffffffffffffffffffff') . "\n" . (pow(2, 128));
?>
helpmedalph at gmail dot com
8 年前
函式 hex2rgb($hex) {
if ($hex[0]=='#') $hex = substr($hex,1);
if (strlen($hex)==3){
$hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
}
$int = hexdec($hex);
return array("red" => 0xFF & ($int >> 0x10), "green" => 0xFF & ($int >> 0x8), "blue" => 0xFF & $int);
}
Manithu
17 年前
這個小函式會根據您提供的顏色返回對比的前景顏色(黑色或白色)

<?php

function getContrastColor($color)
{
return (
hexdec($color) > 0xffffff/2) ? '000000' : 'ffffff';
}

?>

這個函式會返回相反的顏色(負片)

<?php

function negativeColor($color)
{
//取得紅色、綠色和藍色
$r = substr($color, 0, 2);
$g = substr($color, 2, 2);
$b = substr($color, 4, 2);

//反轉它們,它們現在是十進位
$r = 0xff-hexdec($r);
$g = 0xff-hexdec($g);
$b = 0xff-hexdec($b);

//現在將它們轉換為十六進位並返回。
return dechex($r).dechex($g).dechex($b);
}

?>
zubfatal, root at it dot dk
19 年前
這取代了我之前的類別。
我在 rgb2hex 函式中添加了一些輸入檢查。
它也為一位數的值返回了不正確的十六進位值。

color::rgb2hex(array(0,0,0)) 會輸出 000 而不是 00000。

<?php

/**
* Convert colors
*
* Usage:
* color::hex2rgb("FFFFFF")
* color::rgb2hex(array(171,37,37))
*
* @author Tim Johannessen <root@it.dk>
* @version 1.0.1
*/

class color {

/**
* Convert HEX colorcode to an array of colors.
* @return array Returns the array of colors as array(red,green,blue)
*/

function hex2rgb($hexVal = "") {
$hexVal = eregi_replace("[^a-fA-F0-9]", "", $hexVal);
if (
strlen($hexVal) != 6) { return "ERR: Incorrect colorcode, expecting 6 chars (a-f, 0-9)"; }
$arrTmp = explode(" ", chunk_split($hexVal, 2, " "));
$arrTmp = array_map("hexdec", $arrTmp);
return array(
"red" => $arrTmp[0], "green" => $arrTmp[1], "blue" => $arrTmp[2]);
}

/**
* Convert RGB colors to HEX colorcode
* @return string Returns the converted colors as a 6 digit colorcode
*/
function rgb2hex($arrColors = null) {
if (!
is_array($arrColors)) { return "ERR: Invalid input, expecting an array of colors"; }
if (
count($arrColors) < 3) { return "ERR: Invalid input, array too small (3)"; }

array_splice($arrColors, 3);

for (
$x = 0; $x < count($arrColors); $x++) {
if (
strlen($arrColors[$x]) < 1) {
return
"ERR: One or more empty values found, expecting array with 3 values";
}

elseif (
eregi("[^0-9]", $arrColors[$x])) {
return
"ERR: One or more non-numeric values found.";
}

else {
if ((
intval($arrColors[$x]) < 0) || (intval($arrColors[$x]) > 255)) {
return
"ERR: Range mismatch in one or more values (0-255)";
}

else {
$arrColors[$x] = strtoupper(str_pad(dechex($arrColors[$x]), 2, 0, STR_PAD_LEFT));
}
}
}

return
implode("", $arrColors);
}

}

?>
k10206 at naver dot com
17 年前
<?
function hexrgb($hexstr) {
$int = hexdec($hexstr);

return array("red" => 0xFF & ($int >> 0x10), "green" => 0xFF & ($int >> 0x8), "blue" => 0xFF & $int);
}
?>
Walter Wlodarski
16 年前
我最喜歡的、多用途、雙向解決方案之一,是我多年前寫的

function bgr2rgb($cr) { // 雙向
return (($cr & 0x0000FF) << 16 | ($cr & 0x00FF00) | ($cr & 0xFF0000) >> 16);
}

您可能希望這樣使用

function hex2cr($hex) { // 去除任何前導字元,例如 #
return bgr2rgb(hexdec($hex));
}

function cr2hex($cr) { // 常見的 HTML 格式,#rrggbb
return '#'.str_pad(strtoupper(dechex(bgr2rgb($cr))), 6, '0', STR_PAD_LEFT);
}

而且,如果您像我一樣容易打錯函式名稱,可以使用同義詞

function rgb2bgr($val) { return bgr2rgb($val); }
andy at haveland dot com
14 年前
以下是一個在十六進位字串和字元之間轉換的簡短範例

<?php
print hextostr("616E647940686176656C616E642E636F6D")."\n";

print
strtohex("Knowledge is power")."\n";

function
hextostr($x) {
$s='';
foreach(
explode("\n",trim(chunk_split($x,2))) as $h) $s.=chr(hexdec($h));
return(
$s);
}

function
strtohex($x) {
$s='';
foreach(
str_split($x) as $c) $s.=sprintf("%02X",ord($c));
return(
$s);
}
?>
Rosberg - rosberglinhares at gmail dot com
14 年前
正確的版本是

function bchexdec($hex) {
static $hexdec = array(
"0" => 0,
"1" => 1,
"2" => 2,
"3" => 3,
"4" => 4,
"5" => 5,
"6" => 6,
"7" => 7,
"8" => 8,
"9" => 9,
"A" => 10,
"B" => 11,
"C" => 12,
"D" => 13,
"E" => 14,
"F" => 15);
);

$dec = 0;

for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
$factor = $hexdec[$hex[$i]];
$dec = bcadd($dec, bcmul($factor, $e));
}

return $dec;
}
}

jose dot rob dot jr at gmail dot com
15 年前
我寫了這些函式,要把最多 64 個 ID 打包成一個 MySQL 無號bigint。

ID 不能重複,必須 <= 位元限制且 > 0。

這些函式使用 PHP 32 位元的 int 作為無號整數,因為我們實際上並未讀取數字,只讀取位元。 因此 0xFFFFFFFF 顯示 -1,但位元仍然存在(在 Linux 2.6 i686 和 x86_64 上測試過)。

---

這是另一種進行十六進位到二進位轉換的方法。

<?php
函數 hexbin($hex, $padding = false)
{
// 驗證
$hex = preg_replace('/^(0x|X)?/i', '', $hex);
$hex = preg_replace('/[[:blank:]]/', '', $hex);
if(empty(
$hex))
{
$hex = '0';
}
if(!
preg_match('/^[0-9A-F]*$/i', $hex))
{
trigger_error('參數不是十六進制數', E_USER_WARNING);
return
false;
}

// 轉換
$bin = '';
$hex = array_reverse(str_split($hex));
foreach(
$hex as $n)
{
$n = hexdec($n);
for(
$i = 1; $i <= 8; $i <<= 1)
{
$bin .= ($i & $n)? '1' : '0';
}
if(
$padding)
{
$bin .= ' ';
}
}
return
ltrim(strrev($bin));
}

// 測試
echo "<b>除錯:</b> <pre>";

// 隨機選擇的填補數字
var_dump(hexbin('00FF FF8F 7F3F FF1F', true));
// string(79) "0000 0000 1111 1111 1111 1111 1000 1111 0111 1111 0011 1111 1111 1111 0001 1111"

// 黃色 RGB
var_dump(hexbin('0xF8F800'));
// string(24) "111110001111100000000000"

// 綠色 RGB (填補)
var_dump(hexbin('0x008800', true));
//string(29) "0000 0000 1000 1000 0000 0000"

die("\n<br>除錯");

?>

玩得開心 ;D
bishop
19 年前
強健的十六進位轉 RGB 顏色轉換器,就像 brian at sagesport dot com 想要的,只是程式碼行數少很多。此外,還可讓您以字串或陣列方式返回結果。

<?php
function &hex2rgb($hex, $asString = true)
{
// 去除任何前導 #
if (0 === strpos($hex, '#')) {
$hex = substr($hex, 1);
} else if (
0 === strpos($hex, '&H')) {
$hex = substr($hex, 2);
}

// 拆分成十六進位三元組
$cutpoint = ceil(strlen($hex) / 2)-1;
$rgb = explode(':', wordwrap($hex, $cutpoint, ':', $cutpoint), 3);

// 將每個元組轉換為十進位
$rgb[0] = (isset($rgb[0]) ? hexdec($rgb[0]) : 0);
$rgb[1] = (isset($rgb[1]) ? hexdec($rgb[1]) : 0);
$rgb[2] = (isset($rgb[2]) ? hexdec($rgb[2]) : 0);

return (
$asString ? "{$rgb[0]} {$rgb[1]} {$rgb[2]}" : $rgb);
}
?>

可處理 2、3 和 6 個字元的顏色代碼,包含前導 # 或 &H。
cgarvis at gmail dot com
18 年前
這是我的 hex2rgb 版本,用於將網頁顏色轉換為 24 位元顏色。

<?php
function hex2rgb_webcolors($hex) {
$hex = eregi_replace("[^a-fA-F0-9]", "", $hex);
switch(
strlen($hex) ) {
case
2:
$hex = substr($hex,0,2)."0000";
break;
case
3:
$hex = substr($hex,0,1).substr($hex,0,1)
.
substr($hex,1,1).substr($hex,1,1)
.
substr($hex,2,1).substr($hex,2,1);
break;
case
4:
$hex = substr($hex,0,4)."00";
break;
case
6:
break;
default:
$hex = 0;
break;
}
return
hexdec($hex);
}
?>
repley at freemail dot it
18 年前
從一種顏色漸變到另一種顏色……產生漸層效果。適用於動態長條圖。

<?php
//MultiColorFade(array hex-colors, int steps)
function MultiColorFade($hex_array, $steps) {

$tot = count($hex_array);
$gradient = array();
$fixend = 2;
$passages = $tot-1;
$stepsforpassage = floor($steps/$passages);
$stepsremain = $steps - ($stepsforpassage*$passages);

for(
$pointer = 0; $pointer < $tot-1 ; $pointer++) {

$hexstart = $hex_array[$pointer];
$hexend = $hex_array[$pointer + 1];

if(
$stepsremain > 0){
if(
$stepsremain--){
$stepsforthis = $stepsforpassage + 1;
}
}else{
$stepsforthis = $stepsforpassage;
}

if(
$pointer > 0){
$fixend = 1;
}

$start['r'] = hexdec(substr($hexstart, 0, 2));
$start['g'] = hexdec(substr($hexstart, 2, 2));
$start['b'] = hexdec(substr($hexstart, 4, 2));

$end['r'] = hexdec(substr($hexend, 0, 2));
$end['g'] = hexdec(substr($hexend, 2, 2));
$end['b'] = hexdec(substr($hexend, 4, 2));

$step['r'] = ($start['r'] - $end['r']) / ($stepsforthis);
$step['g'] = ($start['g'] - $end['g']) / ($stepsforthis);
$step['b'] = ($start['b'] - $end['b']) / ($stepsforthis);

for(
$i = 0; $i <= $stepsforthis-$fixend; $i++) {

$rgb['r'] = floor($start['r'] - ($step['r'] * $i));
$rgb['g'] = floor($start['g'] - ($step['g'] * $i));
$rgb['b'] = floor($start['b'] - ($step['b'] * $i));

$hex['r'] = sprintf('%02x', ($rgb['r']));
$hex['g'] = sprintf('%02x', ($rgb['g']));
$hex['b'] = sprintf('%02x', ($rgb['b']));

$gradient[] = strtoupper(implode(NULL, $hex));
}
}

$gradient[] = $hex_array[$tot-1];

return
$gradient;
}
//end MultiColorFade()

//start test
$multi_hex_array = array();
$multi_hex_array[] = array('FF0000','FFFF00');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF','0000FF');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF','0000FF','000000');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF','0000FF','000000','FFFFFF');

foreach(
$multi_hex_array as $hex_array){

$totcolors = count($hex_array);
$steps = 44;

$a = MultiColorFade($hex_array, $steps);
$tot = count($a);

$table = '<table border=1 width="300">' . "\n";

for (
$i = 0; $i < $tot; $i++){
$table .= ' <tr><td bgcolor="' . $a[$i] . '">' . ($i+1) .'</td><td><pre>' . $a[$i] . '</pre></td></tr>' . "\n";
}

$table .= '</table><br /><br />';

echo
'<br />Demanded steps = ' . $steps . '<br />';
echo
'Returned steps = ' . $tot;

if(
$steps == $tot){
echo
'<br />OK.' . $steps . ' = ' . $tot . '<br />';
}else{
echo
'<br /><span style="color:#FF0000">FAILED! Demanded steps and returned steps are NOT equal!: ' . $steps . ' != ' . $tot . '</span><br />';
}

echo
$table;

}
//end test
?>

Repley.
detrate at hotmail dot com
19 年前
我寫這段程式碼是用於一個小的 phpbb 模組。它用於從資料庫中獲取十六進位值,並使其顏色值減少 20(十進位),產生較暗的顏色。

範例:#336699 轉換為 #1f5285

<?php

$row1
= "336699"; // 顏色
$c = 20; // 差值

$rgb = array(substr($row1,0,2), substr($row1,2,2), substr($row1,4,2));

for(
$i=0; $i < 3; $i++)
{
if((
hexdec($rgb[$i])-$c) >= 0)
{
$rgb[$i] = hexdec($rgb[$i])-$c;

$rgb[$i] = dechex($rgb[$i]);
if(
hexdec($rgb[$i]) <= 9)
$rgb[$i] = "0".$rgb[$i];
} else {
$rgb[$i] = "00";
}
}

$row2 = $rgb[0].$rgb[1].$rgb[2];

?>
joquius at kakugo dot com
16 年前
協助十六進制字串恢復正常

<?php
$str
= preg_replace_callback ("/%([a-zA-Z0-9]{2})/", create_function ('$matches', 'return chr (hexdec ($matches[1]));'), $str);
?>
this1is4me at hotmail dot com
16 年前
回覆 Amit Yadav 的文章(十六進制轉二進制)

function binfromdec($num)
{
$primary = "bit";
for ($i=1; $i<=16; $i++)
${$primary.$i} = 0;

if ($num & 32768) $bit16 = 1;
if ($num & 16384) $bit15 = 1;
if ($num & 8192) $bit14 = 1;
if ($num & 4096) $bit13 = 1;
if ($num & 2048) $bit12 = 1;
if ($num & 1024) $bit11 = 1;
if ($num & 512) $bit10 = 1;
if ($num & 256) $bit9 = 1;
if ($num & 128) $bit8 = 1;
if ($num & 64) $bit7 = 1;
if ($num & 32) $bit6 = 1;
if ($num & 16) $bit5 = 1;
if ($num & 8) $bit4 = 1;
if ($num & 4) $bit3 = 1;
if ($num & 2) $bit2 = 1;
if ($num & 1) $bit1 = 1;

return ($bit16. $bit15. $bit14. $bit13. $bit12. $bit11. $bit10. $bit9. $bit8. $bit7. $bit6. $bit5. $bit4. $bit3. $bit2. $bit1);
}
maddddidley at yahoo dot com
16 年前
合併兩種 RGB 顏色的函式。

function combineColors($color1, $color2) {

$color1 = str_replace("#", '', $color1);
$color2 = str_replace("#", '', $color2);

$r1 = hexdec(substr($color1, 0, 2));
$g1 = hexdec(substr($color1, 2, 2));
$b1 = hexdec(substr($color1, 4, 2));

$r2 = hexdec(substr($color2, 0, 2));
$g2 = hexdec(substr($color2, 2, 2));
$b2 = hexdec(substr($color2, 4, 2));

$r3 = ceil(($r1 + $r2) / 2);
$g3 = ceil(($g1 + $g2) / 2);
$b3 = ceil(($b1 + $b2) / 2);


$color = rgbhex($r3, $g3, $b3);
return $color = str_replace("#", '', $color);

}
ayadav at infoprocorp dot com
18 年前
來自 Amit Yadav

十六進位轉二進位

$num = hexdec("20DF");
echo binfromdec($num);

function binfromdec($num)
{
if ($num > 32766) return ("過大!");
if ($num & 16384) $bit15 = 1;
if ($num & 8192) $bit14 = 1;
if ($num & 4096) $bit13 = 1;
if ($num & 2048) $bit12 = 1;
if ($num & 1024) $bit11 = 1;
if ($num & 512) $bit10 = 1;
if ($num & 256) $bit9 = 1;
if ($num & 128) $bit8 = 1;
if ($num & 64) $bit7 = 1;
if ($num & 32) $bit6 = 1;
if ($num & 16) $bit5 = 1;
if ($num & 8) $bit4 = 1;
if ($num & 4) $bit3 = 1;
if ($num & 2) $bit2 = 1;
if ($num & 1) $bit1 = 1;

return ("" . $bit15 . $bit14 . $bit13 . $bit12 . $bit11 . $bit10 . $bit9 . $bit8 . $bit7 . $bit6 . $bit5 . $bit4 . $bit3 . $bit2 . $bit1);

}
andreas.schmeiler
21 年前
這是另一個 hex2bin 變體,對我來說效果很好。

function hex2bin($hexdata) {

for ($i=0;$i<strlen($hexdata);$i+=2) {
$bindata.=chr(hexdec(substr($hexdata,$i,2)));
}

return $bindata;
}
To Top