views:

33

answers:

1

Hi, I have used the following php function to create thumbnail image.

function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth ) 
{
  $dir = opendir( $pathToImages );

  while (false !== ($fname = readdir( $dir ))) {  
    $info = pathinfo($pathToImages . $fname);
    if ( strtolower($info['extension']) == 'jpg' ||  strtolower($info['extension']) == 'png' ) 
    {
      // load image and get image size
      if(strtolower($info['extension']) == 'jpg')
      $img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
      else
      $img = imagecreatefrompng( "{$pathToImages}{$fname}" );
      $width = imagesx( $img );
      $height = imagesy( $img );

      // calculate thumbnail size
      $new_width = $thumbWidth;
      $new_height = floor( $height * ( $thumbWidth / $width ) );

      // create a new tempopary image
      $tmp_img = imagecreatetruecolor( $new_width, $new_height );

      // copy and resize old image into new image 
      //imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
      imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

      // save thumbnail into a file
      if(strtolower($info['extension']) == 'jpg')
      imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
      else
      imagepng( $tmp_img, "{$pathToThumbs}{$fname}" );
    }
  }
  // close the directory
  closedir( $dir );
}

Proper thumbnail is created for jpg image. But for png transparent image, thumbnail is created with black background. How do I make function work for png image? Please do suggest me. Thanks in advance.

A: 

I don't remember the exact particulars, but you'll want to read up on, and experiment with imagesavealpha() and imageaplphablending()

If memory serves me correctly, you'll want to set imagealphablending off, and then set imagesavealpha true. (In fact, yes, the manual page for imagesavealpha() implies just that)

So, at the end of your code:

// save thumbnail into a file
if(strtolower($info['extension']) == 'jpg'){
    imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}");
}else{
    imagealphablending($tmp_img,false);
    imagesavealpha($tmp_img,true);
    imagepng( $tmp_img, "{$pathToThumbs}{$fname}" );
}
timdev