这是我写的一些图像类,而后者使用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
的包装类,如果遇到问题,值得一看。
我希望这可以帮助你,祝你好运!