2012-03-03 77 views
4

我需要PHP站點的通用圖像上傳。照片和標誌應該重新調整大小以確保它們不會太大並適合設計。PHP-GD:保留半透明區域

我使用此代碼嘗試它:

function resize($width,$height) { 
    $new_image = imagecreatetruecolor($width, $height); 

    if($this->image_type == PNG or $this->image_type == GIF) { 
     imagealphablending($new_image, false); 
     imagesavealpha($new_image,true); 
     $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127); 
     imagefilledrectangle($new_image, 0, 0, $nWidth, $nHeight, $transparent); 
    } 

    imagecopyresized($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); 
    $this->image = $new_image; 
} 

然而,當我上載有0到255之間的α值區域的圖像,他們得到一個完整的黑色所取代,轉向防混疊區域到黑色邊框。

對於PNG和GIF,完全透明工作正常,只是半透明區域是個問題。

我很抱歉,如果我沒有使用正確的術語來解釋我的問題,也許這就是爲什麼我幾乎找不到它的原因。

+0

請參閱http://stackoverflow.com/questions/8443699/how-to-draw-semi-transparent-rectangle-in-php – 2012-04-01 22:31:13

+1

無法重現,問題可能是其他地方,例如,如果圖像是PNG,是'imagecreatefrompng'用過嗎?你可以用'imagefill'替換'imagefilledrectangle','imagecopyresized'替換'imagecopyresampled',如果你添加'imagealphablending($ this-> image,true);'... – 2012-04-01 22:40:58

回答

1

嘗試:

function resize($width,$height) { 
    $new_image = imagecreatetruecolor($width, $height); 

    if($this->image_type == PNG or $this->image_type == GIF) { 
     imagefill($new_image, 0, 0, IMG_COLOR_TRANSPARENT); 
     imagesavealpha($new_image,true); 
     imagealphablending($new_image, true); 
    } 

    imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); 
    $this->image = $new_image; 
} 

基於this(我知道它的工作原理)。

+0

謝謝,我需要這個。 UPVOTED :) – 2014-12-15 16:01:48