Lanbo
Lanbo

Reputation: 15692

PHP-GD: preserve half-transparent areas

I'm in need of a generic image upload for a PHP site. Photos and Logos should be re-sized to a certain extend to make sure they're not too big and fit the design.

I'm trying it with this code:

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

However, when I upload an image that has areas with alpha-values between 0 and 255, they get replaced by a complete black, turning anti-aliased areas to a black border.

The full transparency works fine for PNG and GIF, merely the half-transparent areas are a problem.

I apologise if I'm not using the correct terms to explain my problem, maybe that's why I hardly found anything on it.

Upvotes: 4

Views: 343

Answers (1)

Alix Axel
Alix Axel

Reputation: 154553

Try:

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

Based on this (which I know it works).

Upvotes: 1

Related Questions