1

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

1 回答 1

0

这一行:

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

看起来很可疑。

如果这是整数除法,那么对于奇数像素宽的图像,您将被截断。尝试:

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

确保您的所有算术都使用实数,最好是双精度数,但是对于您正在处理的范围内的数字,它应该可以在单精度浮点数中工作。

于 2010-07-17T16:43:21.417 回答