裁剪和调整大小理论

时间:2017-09-27 08:44:27

标签: php image laravel theory intervention

我需要一些关于裁剪和调整焦点周围图像大小的理论的一些指导,并带有一个边界框。

在我的情况下,我有不同的图像尺寸要求(例如100x100,500x200,1200x50),不同的定义(1x,2x,3x等)。

这些定义有效地将50x50裁剪后的图像转换为100x100裁剪图像,从而为更高屏幕分辨率的设备提供2倍的清晰度。

我提供了一个用户上传的图像,其中包含x,y焦点和带有两个x,y坐标的边界框(topLeft [x,y],bottomRight [x,y])。

将我的用户提供的图像转换为不同大小和分辨率的各种图像的理论是什么?研究使我找到了一个或另一个,但不是我的所有要求。

在我的特定环境中,我使用的是PHP,Laravel和图像干预库,尽管由于这个问题的性质,这有点无关紧要。

1 个答案:

答案 0 :(得分:1)

这是我在回来时使用GD lib编写的一个图像类。

https://github.com/delboy1978uk/image/blob/master/src/Image.php

我没有根据焦点编写用于调整大小和裁剪的代码,但我确实有一个resizeAndCrop()方法可以在焦点位于焦点的前提下工作:

public function resizeAndCrop($width,$height)
    {
        $target_ratio = $width / $height;
        $actual_ratio = $this->getWidth() / $this->getHeight();

        if($target_ratio == $actual_ratio){
            // Scale to size
            $this->resize($width,$height);

        } elseif($target_ratio > $actual_ratio) {
            // Resize to width, crop extra height
            $this->resizeToWidth($width);
            $this->crop($width,$height,true);

        } else {
            // Resize to height, crop additional width
            $this->resizeToHeight($height);
            $this->crop($width,$height,true);
        }
    }

这是crop()方法,您可以将焦点设置为左侧,中间或右侧:

/**
 * @param $width
 * @param $height
 * @param string $trim
 */
public function crop($width,$height, $trim = 'center')
{
    $offset_x = 0;
    $offset_y = 0;
    $current_width = $this->getWidth();
    $current_height = $this->getHeight();
    if($trim != 'left')
    {
        if($current_width > $width) {
            $diff = $current_width - $width;
            $offset_x = ($trim == 'center') ? $diff / 2 : $diff; //full diff for trim right
        }
        if($current_height > $height) {
            $diff = $current_height - $height;
            $offset_y = ($trim = 'center') ? $diff / 2 : $diff;
        }
    }
    $new_image = imagecreatetruecolor($width,$height);
    imagecopyresampled($new_image,$this->_image,0,0,$offset_x,$offset_y,$width,$height,$width,$height);
    $this->_image = $new_image;
}

我不打扰解释imagecopyresampled(),因为你只是在寻找裁剪背后的理论,但文档在这里http://php.net/manual/en/function.imagecopyresampled.php

请记住,使用PHP的GD库调整图像大小是内存密集型的,具体取决于图像的大小。我喜欢使用imagemagick,PHP有一个名为Imagick的包装类,值得一看,如果遇到麻烦。

我希望这对你有所帮助,祝你好运!

相关问题