2010-07-17 35 views
0

我使用一個基於某些選項自動裁剪圖像的類。問題是,當圖像具有一定的寬度和高度時,圖像會被裁剪,但黑色像素的1px列會被添加到圖像的右側。我認爲問題在於用於生成新圖像尺寸的數學...也許當高度和寬度的劃分給出十進制數然後平方不完美並且黑色像素被添加時...用GD庫修剪圖像爲完美廣場的問題

任何解決方案?

這是我如何調用該對象:

$resizeObj = new resize($image_file); // *** 1) Initialise/load image 
      $resizeObj -> resizeImage(182, 182, 'crop'); // *** 2) Resize image 
      $resizeObj -> saveImage($destination_path, 92); // *** 3) Save image 

我談論類的部分:

private function getOptimalCrop($newWidth, $newHeight) 
    { 

     $heightRatio = $this->height/$newHeight; 
     $widthRatio = $this->width/$newWidth; 

     if ($heightRatio < $widthRatio) { 
      $optimalRatio = $heightRatio; 
     } else { 
      $optimalRatio = $widthRatio; 
     } 

     $optimalHeight = $this->height/$optimalRatio; 
     $optimalWidth = $this->width/$optimalRatio; 

     return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight); 
    } 

    private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight) 
    { 
     // *** Find center - this will be used for the crop 
     $cropStartX = ($optimalWidth/2) - ($newWidth /2); 
     $cropStartY = 0; // start crop from top 

     $crop = $this->imageResized; 
     //imagedestroy($this->imageResized); 

     // *** Now crop from center to exact requested size 
     $this->imageResized = imagecreatetruecolor($newWidth , $newHeight); 
     imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight); 
    } 

更新:

也許改變這個:

$heightRatio = $this->height/$newHeight; 
$widthRatio = $this->width/$newWidth; 

與此:

$heightRatio = round($this->height/$newHeight); 
$widthRatio = round($this->width/$newWidth); 
+0

如果有幫助,我知道我確信我在http://php.net/manual/en/function.imagecopyresampled.php的評論中複製了一個方形縮略圖生成示例來完成這項工作,並且它正在工作對於我來說足夠了。不幸的是,我在工作,而代碼來自我目前無法訪問的個人項目,所以我不能告訴你它是哪一個 - 但這裏只有一對夫婦。 – 2010-07-21 08:42:15

回答

0

這條線:

$cropStartX = ($optimalWidth/2) - ($newWidth /2); 

看起來很可疑。

如果這是整數除法,那麼對於奇數像素寬的圖像,您將得到截斷。嘗試:

$cropStartX = ($optimalWidth/2.0) - ($newWidth/2.0); 

確保您所有的算法使用實數,最好是雙精度的,但在範圍內的數字,你正在處理這應該是OK的單精度浮點數的工作。

+0

如何確保所有算術使用實數? – Jonathan 2010-07-17 16:47:41

+0

@Jonathan - 如果這是C#或C++,我會說他們聲明爲'double',但由於PHP沒有強類型,我不確定是否有「正確」的方式。 – ChrisF 2010-07-17 17:00:12

+0

PHP確實支持類型轉換http://php.net/manual/en/language.types.type-juggling.php#language.types.typecasting – Iiridayn 2010-12-22 20:04:24