2011-07-01 45 views
1

我正在寫一個PHP腳本使用imagick擴展名。我想讓腳本執行的操作是拍攝用戶上傳的圖像,並從中創建一個200x128縮略圖。PHP Imagick調整大小與黑色背景

這不是唯一的事情。顯然,並非所有圖像都適合200x128的寬高比。所以我想要的腳本是填補黑色背景的差距。

現在,圖像調整大小,但沒有黑色背景,大小也不正確。基本上,圖像總是應該是200x128。調整大小後的圖像將放在中間,其餘內容將填充黑色。

任何想法?

這裏是我的代碼:

function portfolio_image_search_resize($image) { 

    // Check if imagick is loaded. If not, return false. 
    if(!extension_loaded('imagick')) { return false; } 

    // Set the dimensions of the search result thumbnail 
    $search_thumb_width = 200; 
    $search_thumb_height = 128; 

    // Instantiate class. Then, read the image. 
    $IM = new Imagick(); 
    $IM->readImage($image); 

    // Obtain image height and width 
    $image_height = $IM->getImageHeight(); 
    $image_width = $IM->getImageWidth(); 

    // Determine if the picture is portrait or landscape 
    $orientation = ($image_height > $image_width) ? 'portrait' : 'landscape'; 

    // Set compression and file type 
    $IM->setImageCompression(Imagick::COMPRESSION_JPEG); 
    $IM->setImageCompressionQuality(100); 
    $IM->setResolution(72,72); 
    $IM->setImageFormat('jpg'); 

    switch($orientation) { 

     case 'portrait': 

      // Since the image must maintain its aspect ratio, the rest of the image must appear as black 
      $IM->setImageBackgroundColor("black"); 

      $IM->scaleImage(0, $search_thumb_height); 

      $filename = 'user_search_thumbnail.jpg'; 

      // Write the image 
      if($IM->writeImage($filename) == true) { 
       return true; 
      } 
      else { 
       return false; 
      } 
      break; 

     case 'landscape': 

      // The aspect ratio of the image might not match the search result thumbnail (1.5625) 
      $IM->setImageBackgroundColor("black"); 

      $calc_image_rsz_height = ($image_height/$image_width) * $search_thumb_width; 

      if($calc_image_rsz_height > $search_thumb_height) { 
       $IM->scaleImage(0, $search_thumb_height); 
      } 
      else { 
       $IM->scaleImage($search_thumb_width, 0); 
      } 

      $filename = 'user_search_thumbnail.jpg'; 

      if($IM->writeImage($filename) == true) { 
       return true; 
      } 
      else { 
       return false; 
      } 

     break; 

    } 

} 
+0

可以在200x128px的畫布中畫一個較小的圖像,比如128x128px? –

+0

我對Imagick瞭解不多,但是從我對圖形的一點了解,我認爲你應該創建一個黑色填充的矩形,並在其上覆蓋縮略圖。 Imagick應該不難,對吧? – afaolek

+1

PS:嘗試把'$ IM-> setImageBackgroundColor(「黑色」);'調整大小後語句 – afaolek

回答

0

exec('convert -define jpeg:size=400x436 big_image.jpg -auto-orient -thumbnail 200x218 -unsharp 0x.5 thumbnail.gif');

您需要安裝ImageMagick的。

sudo apt-get install imagemagick

在看看: http://www.imagemagick.org/Usage/thumbnails/#creation

它顯示了進一步的例子,以及如何墊出來的縮略圖,您選擇的背景色。

+0

我相信這個問題是特定於iMagick,imagemagick的PHP包裝 – kaese