【问题标题】:Crop and resize theory裁剪和调整大小理论
【发布时间】:2017-09-27 08:44:27
【问题描述】:

我需要一些关于围绕焦点裁剪和调整图像大小以及边界框的理论指导。

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

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

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

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

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

【问题讨论】:

    标签: php image laravel theory intervention


    【解决方案1】:

    这是我之前写的一个图像类,它使用了 GD 库。

    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的包装类,如果遇到麻烦值得看看。

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

    【讨论】:

      猜你喜欢
      • 2018-09-22
      • 1970-01-01
      • 1970-01-01
      • 2010-10-03
      • 1970-01-01
      • 2011-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多