PHP-GD: Resize Transparent Image PNG & GIF

Written on July 10, 2008 – 10:21 pm | by vandai |

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. ?>


Full source code for resizing image:

filename: imageresize.php
  1. <?
  2. function resize($img, $w, $h, $newfilename) {
  3.  
  4.  //Check if GD extension is loaded
  5.  if (!extension_loaded('gd') && !extension_loaded('gd2')) {
  6.   trigger_error("GD is not loaded", E_USER_WARNING);
  7.   return false;
  8.  }
  9.  
  10.  //Get Image size info
  11.  $imgInfo = getimagesize($img);
  12.  switch ($imgInfo[2]) {
  13.   case 1: $im = imagecreatefromgif($img); break;
  14.   case 2: $im = imagecreatefromjpeg($img);  break;
  15.   case 3: $im = imagecreatefrompng($img); break;
  16.   default:  trigger_error('Unsupported filetype!', E_USER_WARNING);  break;
  17.  }
  18.  
  19.  //If image dimension is smaller, do not resize
  20.  if ($imgInfo[0] <= $w && $imgInfo[1] <= $h) {
  21.   $nHeight = $imgInfo[1];
  22.   $nWidth = $imgInfo[0];
  23.  }else{
  24.                 //yeah, resize it, but keep it proportional
  25.   if ($w/$imgInfo[0] > $h/$imgInfo[1]) {
  26.    $nWidth = $w;
  27.    $nHeight = $imgInfo[1]*($w/$imgInfo[0]);
  28.   }else{
  29.    $nWidth = $imgInfo[0]*($h/$imgInfo[1]);
  30.    $nHeight = $h;
  31.   }
  32.  }
  33.  $nWidth = round($nWidth);
  34.  $nHeight = round($nHeight);
  35.  
  36.  $newImg = imagecreatetruecolor($nWidth, $nHeight);
  37.  
  38.  /* Check if this image is PNG or GIF, then set if Transparent*/  
  39.  if(($imgInfo[2] == 1) OR ($imgInfo[2]==3)){
  40.   imagealphablending($newImg, false);
  41.   imagesavealpha($newImg,true);
  42.   $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
  43.   imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
  44.  }
  45.  imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);
  46.  
  47.  //Generate the file, and rename it to $newfilename
  48.  switch ($imgInfo[2]) {
  49.   case 1: imagegif($newImg,$newfilename); break;
  50.   case 2: imagejpeg($newImg,$newfilename);  break;
  51.   case 3: imagepng($newImg,$newfilename); break;
  52.   default:  trigger_error('Failed resize image!', E_USER_WARNING);  break;
  53.  }
  54.    
  55.    return $newfilename;
  56. }
  57. ?>

Script usage:

filename showimage.php
  1. <?
  2. include_once("resizeimage.php");
  3. $image = "some/dir/image.png"; // File image location
  4. $newfilename = "thumb_image.png"; // New file name for thumb
  5. $w = 100;
  6. $h = 100;
  7.  
  8. $thumbnail = resize($img, $w, $h, $newfilename);
  9.  
  10. echo "<img src='".$thumbnail."'>";
  11. ?>

No, i’m not provide any downloadable source-code.
Just copy-paste this code, and use it well.

  1. 9 Responses to “PHP-GD: Resize Transparent Image PNG & GIF”

  2. By hendry on Jul 19, 2008 | Reply

    wow just simple, it’s work !!! thanks

  3. By joy on Jul 24, 2008 | Reply

    wow nice!!!

  4. By rivaldo on Jul 25, 2008 | Reply

    Fantastic job!

  5. By kurroman on Jul 31, 2008 | Reply

    First, my english is a little… :)

    I have a problem. Im trying to open a png file with a transparent object inside (not all, just the border). Then i write some text and save the file as another .png file.

    The problem is that de quality of the object border is too bad (¿pixeled?). How can i fix that?

  6. By vandai on Jul 31, 2008 | Reply

    have u tried this code?
    i have the same problem with you before.
    the image quality is sooo bad.

    but this code has fix it.

  7. By Christopher on Aug 8, 2008 | Reply

    Many thanks! Just the help I needed.

  8. By TAF on Aug 23, 2008 | Reply

    The script gets hinkey if you have a file that is smaller in height than the minimum, but longer in width… you end up resizing huge in width to get the right height.

    It needs to resize down by which ever length is too long, or both if they are both too long.

    I HAVE AN IMPROVEMENT THAT FIXES THIS:

    //If image dimension is smaller, do not resize
    if ($imgInfo[0] <= $w && $imgInfo[1] = $w && $imgInfo[1] <= $h) {
    $nWidth = $w;
    $nHeight = $imgInfo[1]*($w/$imgInfo[0]);
    }else{
    //if h larger but not w, resize it, but keep it proportional
    if ($imgInfo[0] = $h) {
    $nWidth = $imgInfo[0]*($h/$imgInfo[1]);
    $nHeight = $h;
    }else{
    //if both w and h are larger, resize it, but keep it proportional
    if ($w/$imgInfo[0] > $h/$imgInfo[1]) {
    $nWidth = $w;
    $nHeight = $imgInfo[1]*($w/$imgInfo[0]);
    }else{
    $nWidth = $imgInfo[0]*($h/$imgInfo[1]);
    $nHeight = $h;
    }
    }
    }
    }
    $nWidth = round($nWidth);
    $nHeight = round($nHeight);

  9. By ghprod on Aug 29, 2008 | Reply

    this is one i’m looking for :)

    Thnx for this great code!

  10. By TAF on Aug 29, 2008 | Reply

    Ahhh… just realised through lotsa testing that the line:

    if ($w/$imgInfo[0] > $h/$imgInfo[1]) {

    Should be

    if ($w/$imgInfo[0] < $h/$imgInfo[1]) {

Post a Comment

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 :