I’m attempting to resize pngs with transparent backgrounds in PHP and the code samples I’ve found online don’t work for me. Here’s the code I’m using, advice will be much appreciated!
$this->image = imagecreatefrompng($filename); imagesavealpha($this->image, true); $newImage = imagecreatetruecolor($width, $height); // Make a new transparent image and turn off alpha blending to keep the alpha channel $background = imagecolorallocatealpha($newImage, 255, 255, 255, 127); imagecolortransparent($newImage, $background); imagealphablending($newImage, false); imagesavealpha($newImage, true); imagecopyresampled($newImage, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); $this->image = $newImage; imagepng($this->image,$filename);
Update By ‘not working’ I meant to say the background color changes to black when I resize pngs.
From what I can tell, you need to set the blending mode to
false, and the save alpha channel flag totruebefore you do the imagecolorallocatealpha()UPDATE : This code is working only on background transparent with opacity = 0. If your image have 0 < opacity < 100 it’ll be black background.