2012-03-03 108 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