2012-05-23 107 views
1

我將使用在所有這些變量:PNG文件不保持透明度?

$ROOTDIR = $_SERVER["DOCUMENT_ROOT"]; 
$ROOTFILE = "http://www.scottandjessiecooper.com/webtutorials/images/smiley.png"; 
$NEWFILE = "$ROOTDIR/images/tmp/new_smiley.png"; 

當我使用這個功能,我有透明度沒有問題

function save_image($root, $saveto){ 
    copy($root, $saveto); 
} 
save_image($ROOTFILE, $NEWFILE); // root can be file or url 

但是我NEED使用的IMAGE_RESOURCE,所以我凸輪操縱ROOTFILE如果需要

所以我treid這個:

if (file_exists($NEWFILE)) unlink ($NEWFILE); 
$image = imagecreatefrompng($ROOTFILE); 
imagepng($image, $NEWFILE); 
imagedestroy($image); 

現在,當我使用這個:

<img src="<?=$NEWFILE?>" /> 

我失去了透明度。背景變黑!

所以,我試圖輸出圖像,以確保它不是節省導致問題:

if (file_exists($NEWFILE)) unlink ($NEWFILE); 
$image = imagecreatefrompng($ROOTFILE); 
header('Content-Type: image/png'); 
imagepng($image); 
imagedestroy($image); 

依然無果......

幫助?

回答

3

您需要啓用alpha混合,並保存阿爾法。我在谷歌搜索後10秒後發現: http://www.php.net/manual/en/function.imagecreatefrompng.php#43024

+0

我剛剛搜索「imagecreatefrompng透明度」。 – prehfeldt

+0

我閱讀'imagecreatefrompng'的函數文檔,發現沒有用,我的壞 –

+0

我也發現保存8/16/24 PNG圖像透明度和使用多次一些腳本的困難,產生一些大的PHP塊試圖覆蓋每一個案例(真彩色或256等)。不是那麼容易的東西。 – 2012-05-23 11:25:40

0

如果背景是黑色的,請嘗試以下操作:

$black = imagecolorallocate($im, 0, 0, 0); 
// Make the background transparent 
imagecolortransparent($im, $black); 

(PNG圖像中的透明度是thorugh PHP從來沒有完美的)

+0

你說的png的透明度不是很好的PHP,有沒有另一種方式? –

+0

這個問題是,它需要所有的黑色,並將其變爲透明。我只是想保持原來的透明度。有任何想法嗎? –

+0

你檢查了imagemagick功能?但如果prehfeldt的答案讓你排序,使用(並給他一個打勾!) – Robbie

1

這有幫助嗎?

$info = getimagesize("smiley.png"); 
$image = imagecreatefrompng("smiley.png"); 
$image_new = imagecreatetruecolor($info[0],$info[1]);  
if (($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG)) { 
    $trnprt_indx = imagecolortransparent($image); 
    if ($trnprt_indx >= 0) { 
    $trnprt_color = imagecolorsforindex($image, $trnprt_indx); 
    $trnprt_indx = imagecolorallocate($image_new, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']); 
    imagefill($image_new, 0, 0, $trnprt_indx); 
    imagecolortransparent($image_new, $trnprt_indx); 
    } 
    elseif ($info[2] == IMAGETYPE_PNG) { 
    imagealphablending($image_new, false); 
    $color = imagecolorallocatealpha($image_new, 0, 0, 0, 127); 
    imagefill($image_new, 0, 0, $color); 
    imagesavealpha($image_new, true); 
    } 
} 
imagecopy($image_new,$image,0,0,0,0,$info[0],$info[1]); 
imagepng($image_new,"smiley2.png"); 
1

這裏的問題不在GDPHP

問題出在Photoshop中。

如果您保存PNG文件,而您在RGB mode而不是Indexed mode

0

我有這個問題,發現prehfeldt的answer有正確的想法,但並沒有真正幫助我解決這個問題。實際的方式,使節能Alpha通道信息是你將它輸出到文件之前,你的圖像資源調用imagesavealpha

imagesavealpha($image, true); 
imagepng($image, $NEWFILE); 

當你不這樣做,默認情況下會GD保存時丟棄的透明信息或輸出圖像。原因copy並沒有引起你的這個問題,它是一個簡單的字節逐字節拷貝在文件級別,根本不經過任何圖像處理。