這是我寫的一些圖像類,而後者使用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
的包裝類,如果遇到問題,值得一看。
我希望這可以幫助你,祝你好運!