PHP-GD: preserving translucent areas

I need a general image upload for a PHP site. Photographs and logos need to be modified to a certain extent to make sure they are not too large and fit the design.

I am trying to use 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 load an image with areas with alpha values ​​from 0 to 255, they are replaced with completely black, turning the smoothed areas into a black frame.

Full transparency works fine for PNG and GIF, only problems with translucent areas are a problem.

I apologize if I do not use the correct conditions to explain my problem, which is probably why I almost did not find anything on it.

+4
source share
1 answer

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, as I know, works).

+1
source

Source: https://habr.com/ru/post/1399537/


All Articles