如何裁剪图像的垂直和水平居中版本?

时间:2012-10-05 21:08:30

标签: php image resize crop

我目前正在将图像调整为自定义,并保持纵横比:

class ImgResizer {
var $originalFile = '$newName';
function ImgResizer($originalFile = '$newName') {
    $this -> originalFile = $originalFile;
}
function resize($newWidth, $targetFile) {
    if (empty($newWidth) || empty($targetFile)) {
        return false;
    }
    $src = imagecreatefromjpeg($this -> originalFile);
    list($width, $height) = getimagesize($this -> originalFile);
    $newHeight = ($height / $width) * $newWidth;
    $tmp = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    if (file_exists($targetFile)) {
        unlink($targetFile);
    }
    imagejpeg($tmp, $targetFile, 95);
}
}

用法:

$work = new ImgResizer($path);
$work -> resize(200, $path);

但我想获得200x200px版本的图像。它应该垂直和水平居中(基本上得到图像的主要200px)

可能吗?

- 编辑 -

function resize($newWidth, $targetFile) {
    if (empty($newWidth) || empty($targetFile)) {
        return false;
    }
    $src = imagecreatefromjpeg($this -> originalFile);
    list($width, $height) = getimagesize($this -> originalFile);

    $newHeight =  $newWidth;


      if ($width > $newWidth){
       $srcx = $width/2 - $newWidth/2;
       $destx = 0;
   }
   else{
       $srcx = 0;
       $destx = $newWidth/2 - $width/2;
   }
   if ($height > $newHeight){
       $srcy = $height/2 - $newHeight/2;
       $desty = 0;
   }
   else{
       $srcy = 0;
       $desty = $newHeight/2 - $height/2;
   }


     $tmp = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($tmp, $src, $destx, $desty, $srcx, $srcy, $newWidth, $newHeight, $width, $height);


    if (file_exists($targetFile)) {
        unlink($targetFile);
    }
    imagejpeg($tmp, $targetFile, 95);
}

会产生意外情况:HTTP://209.51.221.243/integracion/files/uploads/1_050.JPG

1 个答案:

答案 0 :(得分:1)

尝试

if ($width > $newWidth){
    $srcx = $width/2 - $newWidth/2;
    $destx = 0;
    $w = $newWidth;
}
else{
    $srcx = 0;
    $destx = $newWidth/2 - $width/2;
    $w = $width;
}
if ($height > $newHeight){
    $srcy = $height/2 - $newHeight/2;
    $desty = 0;
    $h = $newHeight;
}
else{
    $srcy = 0;
    $desty = $newHeight/2 - $height/2;
    $h = $keight;
}
imagecopyresampled($tmp, $src, $destx, $desty, $srcx, $srcy, $w, $h, $w, $h);