创建png图像缩略图时出现问题!

时间:2010-07-12 06:06:21

标签: php image png thumbnails transparent

我使用以下php函数创建缩略图。

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 );
}

为jpg图像创建了正确的缩略图。但是对于png透明图像,缩略图是用黑色背景创建的。如何使功能适用于png图像?请建议我。提前谢谢。

2 个答案:

答案 0 :(得分:0)

我不记得确切的细节,但你会想要阅读,并试验imagesavealpha()imageaplphablending()

如果内存正确地为我服务,你需要关闭imagealphablending,然后将imagesavealpha设置为true。 (事实上​​,是的,imagesavealpha()的手册页只是意味着)

所以,在代码的最后:

// 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}" );
}

答案 1 :(得分:0)

你想重新发明轮子吗?使用php Thumbnailer:)

<?php
// load the library
require 'Thumbnailer';

// make callback function
function myfunc(& $thumb) {
   // that will make a image thumbnail square 100x100px
   $thumb->thumbSquare(100)->save('photos/output/'.$thumb->filename);
}

// call batch helper
// find all jpg, png and gif images in /photos/directory
Thumbnailer::batch('myfunc', '/photos/directory/*.{jpg,png,gif}');
?>

这很容易。

相关问题