PHP-GD:保留半透明区域

4

我需要一个通用的图片上传功能,用于PHP网站。为了确保照片和标志不会过大且适合设计,它们应该被重新调整大小。

我正在使用以下代码尝试实现:

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;
}

然而,当我上传一个带有alpha值在0到255之间的区域的图像时,它们被完全黑色替代,将反锯齿区域变成了黑色边框。
PNG和GIF的完全透明度效果很好,只有半透明区域会出现问题。
如果我没有使用正确的术语来解释我的问题,我很抱歉,也许这就是为什么我几乎找不到任何相关资料的原因。

请参见以下链接:https://dev59.com/yV7Va4cB1Zd3GeqPGx4L - Gabriel Santos
1
无法复制,问题可能出现在其他地方。例如,如果图像是PNG格式,请使用imagecreatefrompng。您可以将imagefilledrectangle替换为imagefill,将imagecopyresized替换为imagecopyresampled,另外,如果您添加imagealphablending($this->image, true);,效果会更好... - Dejan Marjanović
1个回答

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(我知道它可行)的内容。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接