2011-07-19 61 views
2
$im = imagecreatefrompng('./test.png'); 
$white = imagecolorallocate($im, 255, 255, 255); 
imagecolortransparent($im, $white); 

此代碼適用於從圖像中移除純白色,但我想要做的是將所有顏色轉換爲alpha百分比。例如中等灰色將是50%透明黑色。因此,如果放置在頂部,中等灰色的圖像會顯示其背後的圖像。使用PHP將圖像轉換爲Alpha透明度

這可能使用PHP或擴展?

+0

也許用於:http://www.php.net/manual/en/function.imagecolorallocatealpha.php –

回答

0

我剛剛爲您編寫並測試了這個腳本。

$imfile = './test.png'; 
$origim = imagecreatefrompng($imfile); 
$im_size = getimagesize($imfile); 

$im = imagecreatetruecolor($im_size[0], $im_size[1]); 
imagealphablending($im, false); 
imagesavealpha($im, true); 

for ($x = 0; $x < $im_size[0]; ++$x){ 
    for ($y = 0; $y < $im_size[1]; ++$y){ 
     $rgb = imagecolorat($origim,- $x, $y); 
     $r = ($rgb >> 16) & 0xFF; 
     $g = ($rgb >> 8) & 0xFF; 
     $b = $rgb & 0xFF; 
     $color = imagecolorallocatealpha($im, 0, 0, 0, intval(($r+$g+$b)/3/255*127)); 
     imagesetpixel($im, $x, $y, $color); 
    } 
} 

它可能在大圖像上有點慢,但它的工作方式就像您想要的那樣。 =)

希望這個答案是可以接受的。祝你好運。

+1

如果我保存圖像'imagepng($ im,'。/ test2.png');'它剛剛出現完全黑色。有任何想法嗎? – Tim

+0

只需更換這條線即可擺脫黑色並將其着色: '$ color = imagecolorallocatealpha($ im,0,0,0,intval(($ r + $ g + $ b)/ 3/255 * 127)) ;' to .. '$ color = imagecolorallocatealpha($ im,$ r,$ b,$ g,intval(($ r + $ g + $ b)/ 3/255 * 127));'' –

相關問題