2009-12-10 50 views
1

下面的函數設計用於輸入十六進制(帶或不帶「#」前綴),並將顏色更新應用於圖像中startPixel和endPixel之間的部分。 (1)提供紅色,綠色,藍色和(2)直接運行文件作爲一個獨立的(即,只是將該函數的內容保存到文件並執行它)。將圖像轉換爲RGB爲圖像功能

但是,我有兩個問題,我似乎無法解決。 (1)我需要傳入一個十六進制,並使函數在不需要rgb硬代碼的情況下工作,(2)我需要該函數在wordpress中的functions.php文件中工作,同時保存我的主題選項。每次我嘗試在保存時調用該函數時,都會收到「無法打開流」錯誤。

`函數:

function set_theme_color($hex) 
    { 
    //hexToRGB($hex); DOES NOT WORK. ALWAYS RETURNS BLACK 
    $token = "images/sidebar-bg"; 

    $red = 0; 
    $green = 0; 
    $blue = 202; 

    $startPixel = 601; 
    $endPixel = 760; 

    $img = imagecreatefromgif('images/sidebar-bg.gif'); 

    $color = imagecolorallocate($img, $red, $green, $blue); 

    for ($i = $startPixel-1; $i < $endPixel; $i++) 
    { 
     imagesetpixel($img, $i, 0, $color); 
    } 

    imagegif($img, $token.'.gif'); 
    } 

    function hexToRGB ($hexColor) 
    { 
    $output = array(); 
    $output['red'] = hexdec($hexColor[0].$hexColor[1]); 
    $output['green'] = hexdec($hexColor[2].$hexColor[3]); 
    $output['blue'] = hexdec($hexColor[4].$hexColor[5]); 

    return $output; 
    } 

    set_theme_color('#cccccc'); 

`

回答

2

你hexToRGB功能沒有采取#號的可能性考慮在內。爲了解析這些顏色代碼,我會使用一個正則表達式:

function hexToRGB ($hexColor) 
{ 
    if(preg_match('/^#?([a-h0-9]{2})([a-h0-9]{2})([a-h0-9]{2})$/i', $hexColor, $matches)) 
    { 
     return array(
      'red' => hexdec($matches[ 1 ]), 
      'green' => hexdec($matches[ 2 ]), 
      'blue' => hexdec($matches[ 3 ]) 
     ); 
    } 
    else 
    { 
     return array(0, 0, 0); 
    } 
} 

您無法打開流錯誤是最有可能是由於文件權限。確保在您嘗試寫入的文件上授予權限模式777。

+0

感謝喬恩,我仍然從十六進制轉換變黑。我怎樣才能從函數中回顯返回的值? – 2009-12-10 15:14:38

+0

你是怎麼調用hexToRGB的? – 2009-12-10 15:31:27

+0

好的,當我使用var_dump(hexToRGB(「cccccc」))它返回什麼似乎是正確的結果集... array(3){[「red」] => int(204)[「green」 ] => int(204)[「blue」] => int(204)} 但是,我仍然從專色轉換變黑。不知道我的set_image_color函數是否正確執行rgb轉換。 你可以回顧一下set_theme_color函數,讓我知道我錯過了什麼嗎? – 2009-12-10 15:34:06