这是我之前写的一个图像类,它使用了 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的包装类,如果遇到麻烦值得看看。
希望对你有帮助,祝你好运!