2

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

Amr SubZero
  • 1,196
  • 5
  • 19
  • 30

1 Answers1

2

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); 
Community
  • 1
  • 1
V-SHY
  • 3,925
  • 4
  • 31
  • 47
  • 1
    try add `imagecolortransparent($image, $color);` after imagecolorallocatealpha()? – V-SHY Mar 11 '14 at 04:46
  • 1
    after add the `imagecolortransparent($image, $color);` only work? – V-SHY Mar 11 '14 at 04:53
  • No it worked from the first code you posted, i didn't change the ($img) with my variable($image) so it didn't work first time but when i changed it, it worked! Thanks again :) I appreciate your help. – Amr SubZero Mar 11 '14 at 04:54
  • 1
    actually my first post variable is $img but I change it to $image after I found yours is different. You are welcome, I learn something also. ^^ – V-SHY Mar 11 '14 at 04:56