title: PHP resizing PNG images generate black background
body: <p>This is the part of the code I use to display or resize and display with Cache headers. It works fine for JPG images. But PNG images get added with black background. This type of questions are available in SO and Google but almost the solutions accepted or suggested are same: <code>imagealphablending</code> - FALSE and <code>imagesavealpha</code> - TRUE. But in my case, nothing works. What would be the problem?</p>
  
  <pre><code>$image_information=getimagesize($img);
  if($image_information['mime']=='image/gif')
  {
      $img=imagecreatefromgif($img);
      $type="gif";
      $image_header="image/gif";
  }
  elseif($image_information['mime']=='image/png')
  {
      $img=imagecreatefrompng($img);
      $type="png";
      $image_header="image/png";
  }
  else
  {
      $img=imagecreatefromjpeg($img);
      $type="jpg";
      $image_header="image/jpeg";
  }
  
  $width=imagesx($img);
  $height=imagesy($img);
  
  if((isset($w))&amp;(!isset($h))) // If Width or Height is posted, calculate the aspect dimensions
  {
      $h=($height/$width*$w);
  }
  
  if((isset($h))&amp;(!isset($w)))
  {
      $w=(($h*$width)/$height);
  }
  
  if(!isset($w))
  {
      $w=$width;
  }
  
  if(!isset($h))
  {
      $h=$height;
  }
  
  
  $new_image=imagecreatetruecolor($w, $h);
  
  if($type=="gif")
  {
      $background=imagecolorallocate($new_image, 0, 0, 0);
      // removing the black from the placeholder
      imagecolortransparent($new_image, $background); 
  }
  elseif($type=="png")
  {
      imagealphablending($new_image, FALSE);
          imagesavealpha($new_image, TRUE);
      $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
          imagefilledrectangle($new_image, 0, 0, $w, $h, $transparent);
  }
  
  imagecopyresampled($new_image,$img,0,0,0,0,$w,$h,$width,$height);
  $seconds_to_cache = 864000; // Add cache headers
  $ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
  header("Expires: $ts");
  header("Pragma: cache");
  header("Cache-Control:max-age=$seconds_to_cache, must-revalidate");
  header("Last-Modified: ".gmdate("D, d M Y H:i:s", $lastModified)." GMT");
  
  
  header('Content-Type: $image_header');
  if($type="jpg")
  imagejpeg($new_image, NULL, 75);
  elseif($type=="png")
  imagepng($new_image, NULL, 75);
  elseif($type=="gif")
  imagegif($new_image, NULL);
  imagedestroy($new_image);
  </code></pre>
  
  <p><strong>Edit</strong>: I saved the image to my system, tried opening in,</p>
  
  <ol>
  <li>Picasa Photo Viewer - Image opens with Black BG.</li>
  <li>Ms Paint - Image opens with Black BG.</li>
  <li>Photoshop CS6 - Error message pops out: Could not open because of Program error.</li>
  </ol>