Question

I've a png image uploading script in my website and i'm scaling down the large images to small size and i'm using this code but it loses the transparent background

$image = $tmp; // Uploaded Image
$maxImgWidth = 224;
$src = imagecreatefrompng($image);
list($width, $height) = getimagesize($image);
$newwidth = $maxImgWidth;
$newheight = ($height / $width) * $newwidth;
$newImage = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($image, true);
imagesavealpha($image, true);
imagecopyresampled($newImage, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagepng($newImage, "../thumb/$name_after-$code.$ext", 1);
imagedestroy($src);
imagedestroy($newImage);

This code makes the image without transparency :

enter image description here

And i want with transparent background like this one :

enter image description here

Was it helpful?

Solution

Sorry I have no experience in PHP but after I read this page, I think you may need add the transparent colour after you set the save alpha is true

imagesavealpha($image, true);
$color = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagefill($image, 0, 0, $color);

if still cannot try add this after imagecolorallocatealpha(),

imagecolortransparent($image, $color); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top