PHP-GD: Resize Transparent Image PNG & GIF
Thursday, July 10th, 2008By default, you will get black background if you resize a transparent image. To fix it, you need set alpha channel imagecolorallocatealpha to 127.
With imagecolorallocatealpha, it will allocate a color for an image.
Usage:
int imagecolorallocatealpha ( resource image, int red, int green, int blue, int alpha)
From PHP manual:
imagecolorallocatealpha() behaves identically to imagecolorallocate() with the addition of the transparency parameter alpha which may have a value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.
Returns FALSE if the allocation failed.
Before using it, you must set to false the blending mode for an image and set true the flag to save full alpha channel information.
Example:
-
<?
-
$newImg = imagecreatetruecolor($nWidth, $nHeight);
-
imagealphablending($newImg, false);
-
imagesavealpha($newImg,true);
-
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
-
imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
-
imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);
-
?>


