2014-09-29 54 views
-1

所以我做了一個這樣的腳本,用php創建縮略圖並且工作正常,但是我正在爲用戶上傳創建縮略圖的這些文件。我有足夠的驗證來知道它正在上傳哪種類型的圖像。允許的一次是(JPG PNG GIF)否我已經創建了上面的腳本。使用PHP創建不同格式的縮略圖

if (pathinfo($fileName,PATHINFO_EXTENSION) == 'png'){ 
       $img = imagecreatefrompng($basePath.'/'.$fileName); 
       $width = imagesx($img); 
       $height = imagesx($img); 

       //Calculateing tumbnails size 
       $newWidth = 100; 
       $newHeight = floor($height*(100/$width)); 

       //Create a new tempoary image 
       $tmpImage = imagecreatetruecolor($newWidth,$newHeight); 

       imagecopyresized($tmpImage,$img,0,0,0,0,$newWidth,$newHeight,$width,$height); 

       imagepng($tmpImage,$pathToTumb.'/'.$fileName); 
      } 
      if (pathinfo($fileName,PATHINFO_EXTENSION) == 'jpg'){ 
       $img = imagecreatefromjpeg($basePath.'/'.$fileName); 
       $width = imagesx($img); 
       $height = imagesx($img); 

       //Calculateing tumbnails size 
       $newWidth = 100; 
       $newHeight = floor($height*(100/$width)); 

       //Create a new tempoary image 
       $tmpImage = imagecreatetruecolor($newWidth,$newHeight); 

       imagecopyresized($tmpImage,$img,0,0,0,0,$newWidth,$newHeight,$width,$height); 

       imagejpeg($tmpImage,$pathToTumb.'/'.$fileName); 
      } 
      if(pathinfo($fileName,PATHINFO_EXTENSION) == 'gif'){ 
       $img = imagecreatefromgif($basePath.'/'.$fileName); 
       $width = imagesx($img); 
       $height = imagesx($img); 

       //Calculateing tumbnails size 
       $newWidth = 100; 
       $newHeight = floor($height*(100/$width)); 

       //Create a new tempoary image 
       $tmpImage = imagecreatetruecolor($newWidth,$newHeight); 

       imagecopyresized($tmpImage,$img,0,0,0,0,$newWidth,$newHeight,$width,$height); 

       imagegif($tmpImage,$pathToTumb.'/'.$fileName); 
      } 

我發現非常重複的是有不同的方式來做到這一點不同的格式?

而且我想會到,如果它甚至有可能做到這一點時,圖像沒有例如延期,如果該文件的名稱只是測試,而不是test.jpg放在

回答

1

如果你發現自己複製並粘貼代碼,您應該將該代碼轉換爲函數。你的代碼可以如下重構:

switch (pathinfo($fileName, PATHINFO_EXTENSION)) { 
    case 'png': 
     $tmpImage = thumb(imagecreatefrompng($basePath.'/'.$fileName)); 
     imagepng($tmpImage,$pathToTumb.'/'.$fileName); 
     break; 
    case 'jpg': 
     $tmpImage = thumb(imagecreatefromjpeg($basePath.'/'.$fileName)); 
     imagejpeg($tmpImage,$pathToTumb.'/'.$fileName); 
     break; 
    case 'gif': 
     $tmpImage = thumb(imagecreatefromgif($basePath.'/'.$fileName)); 
     imagegif($tmpImage,$pathToTumb.'/'.$fileName); 
     break; 
} 

function thumb($img) { 
    $width = imagesx($img); 
    $height = imagesx($img); 

    //Calculateing tumbnails size 
    $newWidth = 100; 
    $newHeight = floor($height*(100/$width)); 

    //Create a new tempoary image 
    $tmpImage = imagecreatetruecolor($newWidth,$newHeight); 

    imagecopyresized($tmpImage,$img,0,0,0,0,$newWidth,$newHeight,$width,$height); 

    return $tmpImage; 
} 

對於檢測的圖像類型沒有文件擴展名,您可以使用exif_imagetype()或者,如果不可用你的主機,getimagesize()上。

+0

功能很棒!謝謝你以後再試一下擴展的事情,謝謝你的幫助。 – Steve 2014-09-29 19:41:45