Archive for July 10th, 2008

PHP-GD: Resize Transparent Image PNG & GIF

Thursday, July 10th, 2008

By 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:

  1. <?
  2. $newImg = imagecreatetruecolor($nWidth, $nHeight);
  3. imagealphablending($newImg, false);
  4. imagesavealpha($newImg,true);
  5. $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
  6. imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
  7. imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);
  8. ?>

(more…)

About Me

Here I'll share my knowledge, discovery and experience related to my hobby and work. Most articles on this site are related to daily life, hobbies, programming, and linux. More

Want to subscribe?

 Subscribe in a reader
Find entries :