我使用一個基於某些選項自動裁剪圖像的類。問題是,當圖像具有一定的寬度和高度時,圖像會被裁剪,但黑色像素的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);
如果有幫助,我知道我確信我在http://php.net/manual/en/function.imagecopyresampled.php的評論中複製了一個方形縮略圖生成示例來完成這項工作,並且它正在工作對於我來說足夠了。不幸的是,我在工作,而代碼來自我目前無法訪問的個人項目,所以我不能告訴你它是哪一個 - 但這裏只有一對夫婦。 – 2010-07-21 08:42:15