2010-01-22 53 views
0

我目前正在研究需要分析多個圖像並找出它們最接近的顏色的應用程序。帶透明度的PHP圖像顏色分析

因此,我發現了一個代碼段正是如此:

function analyzeImageColors($im, $xCount =3, $yCount =3) 
    { 
    //get dimensions for image 
    $imWidth =imagesx($im); 
    $imHeight =imagesy($im); 
    //find out the dimensions of the blocks we're going to make 
    $blockWidth =round($imWidth/$xCount); 
    $blockHeight =round($imHeight/$yCount); 
    //now get the image colors... 
    for($x =0; $x<$xCount; $x++) { //cycle through the x-axis 
     for ($y =0; $y<$yCount; $y++) { //cycle through the y-axis 
     //this is the start x and y points to make the block from 
     $blockStartX =($x*$blockWidth); 
     $blockStartY =($y*$blockHeight); 
     //create the image we'll use for the block 
     $block =imagecreatetruecolor(1, 1); 
     //We'll put the section of the image we want to get a color for into the block 
     imagecopyresampled($block, $im, 0, 0, $blockStartX, $blockStartY, 1, 1, $blockWidth, $blockHeight); 
     //the palette is where I'll get my color from for this block 
     imagetruecolortopalette($block, true, 1); 
     //I create a variable called eyeDropper to get the color information 
     $eyeDropper =imagecolorat($block, 0, 0); 
     $palette =imagecolorsforindex($block, $eyeDropper); 
     $colorArray[$x][$y]['r'] =$palette['red']; 
     $colorArray[$x][$y]['g'] =$palette['green']; 
     $colorArray[$x][$y]['b'] =$palette['blue']; 
     //get the rgb value too 
     $hex =sprintf("%02X%02X%02X", $colorArray[$x][$y]['r'], $colorArray[$x][$y]['g'], $colorArray[$x][$y]['b']); 
     $colorArray[$x][$y]['rgbHex'] =$hex; 
     //destroy the block 
     imagedestroy($block); 
     } 
    } 
    //destroy the source image 
    imagedestroy($im); 
    return $colorArray; 
    } 

問題是每當我提供具有透明性的圖像,GDLib consinders透明度爲黑色,從而產生錯誤的(暗得多)輸出比真的是這樣。

例如該圖標,其中圍繞箭頭的白色區域實際上是透明的:

example http://img651.imageshack.us/img651/995/screenshot20100122at113.png

誰能告訴我如何解決此問題?

回答

1

您需要imageColorTransparent()。 http://www.php.net/imagecolortransparent

透明度是圖像的屬性,而不是顏色。因此,使用像$transparent = imagecolortransparent($im)這樣的東西來查看圖像是否有任何透明度,然後只需忽略$ colorArray中的那個顏色,或者使用其他方法來標識函數返回的透明顏色。這一切都取決於你如何使用返回的數據。

--M