我使用一个基于某些选项自动将图像裁剪为正方形的类。问题是当图像具有一定的宽度和高度时,图像会被裁剪,但会在图像的右侧添加一个 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);