2017-09-27 99 views
0

我需要一些關於使用邊框在焦點周圍裁剪和調整圖像大小的理論指導。作物和調整大小的理論

在我的情況下,我對不同的定義(1x,2x,3x等)有各種不同的圖像尺寸要求(例如100x100,500x200,1200x50)。

這些定義有效地將50x50裁剪圖像轉換爲100x100裁剪圖像,從而爲更高的屏幕定義設備提供了2倍分辨率。

我爲用戶上傳的圖像提供了一個x,y焦點和一個帶有兩個x,y座標(topLeft [x,y],bottomRight [x,y])的邊界框。

什麼理論將我的用戶提供的圖像變成各種不同尺寸和分辨率的圖像?研究使我找到了一個或另一個,但並不是我所有的要求都在一起。

在我的特定環境中,我使用PHP,Laravel和圖像干預庫,儘管由於此問題的性質,這有點不相關。

回答

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的包裝類,如果遇到問題,值得一看。

我希望這可以幫助你,祝你好運!