2010-07-12 77 views
0

我已經使用下面的php函數來創建縮略圖。創建png圖像的縮略圖時出現問題!

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圖像工作?請建議我。提前致謝。

回答

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

這很簡單。