[英]Problem cropping an image to a perfect square with GD library
我使用一個基於某些選項自動將圖像裁剪為正方形的類。 問題是,當圖像具有一定的寬度和高度時,將對圖像進行裁剪,但是會在圖像的右側添加1px的黑色像素列。 我認為問題出在用於生成新圖像尺寸的數學中...也許當高度和寬度的除法給出一個十進制數時,平方並不完美,並且添加了黑色像素...
有什么辦法嗎?
這就是我所說的對象:
$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);
這行:
$cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
看起來可疑。
如果這是整數除法,那么對於像素數為奇數個像素的圖像,您將被截斷。 嘗試:
$cropStartX = ( $optimalWidth / 2.0) - ( $newWidth / 2.0 );
確保您所有的算術都使用實數,最好是雙精度數,但是處理的范圍內的數字應該可以在單精度浮點數中使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.