2014-11-24 67 views
1

我是新來的PHP,我需要幫助。我正在嘗試製作一個簡單的圖庫。我完成了上傳部分畫廊的工作。現在我想從一個文件夾中獲取這些圖像,使它們的縮略圖將它們保存在一個數組,以便我可以稍後顯示它們。 這就是我目前所掙扎的。數組在最後仍爲空。使用php創建並保存一個縮略圖陣列

$folder = 'images/'; 
$filetype = '*.*'; 
$files = glob($folder.$filetype); 
$count = count($files); 
$thumbArray = array(); 

for($i=0; $i<$count; $i++){ 
if(($img = @imagecreatefromstring($files[$i])) !== FALSE) { 

    $width = imagesx($img); 
    $height = imagesy($img); 

    $boxSize = min($width,$height); 
    $boxX = ($width/2) - ($boxSize/2); 
    $boxY = ($height/2) - ($boxSize/2); 
    $thumbArray[$i] = imagecreatetruecolor(100, 100); 
    imagecopyresampled($thumbArray[$i], $img, 0, 0, $boxX, $boxY, 100, 100, $boxSize, $boxSize); 
} 
} 

在此先感謝。

回答

1

在你的代碼的問題是在這條線:

if (($img = @imagecreatefromstring($files[$i])) !== FALSE) { ... } 

似乎從來沒有被執行該語句。

要使用文件名從文件中獲取圖像,應使用imagecreatefromjpeg函數。所以內環路你的代碼應該是這樣的:

$img = imagecreatefromjpeg($files[$i]); 

$width = imagesx($img); 
$height = imagesy($img); 

$boxSize = min($width,$height); 
$boxX = ($width/2) - ($boxSize/2); 
$boxY = ($height/2) - ($boxSize/2); 

$thumbArray[$i] = imagecreatetruecolor(100, 100); 
imagecopyresampled($thumbArray[$i], $img, 0, 0, $boxX, $boxY, 100, 100, $boxSize, $boxSize); 

最後,你可以使用imagejpeg函數來查看在瀏覽器中的結果,或直接將其保存到一個文件中。