【问题标题】:How to crop a verticaly and horizontaly centered version of an image?如何裁剪图像的垂直和水平居中版本?
【发布时间】:2012-10-05 21:08:29
【问题描述】:

我目前正在调整图像大小以保持纵横比:

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

【问题讨论】:

    标签: php image resize crop


    【解决方案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);
    

    【讨论】:

    • @ToniMichelCaubet 再来一次
    • 这行得通。我刚刚意识到这不是我想要的。我想要将图像居中的最大正方形调整为 200x200 像素...这需要很多更改吗?
    猜你喜欢
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    相关资源
    最近更新 更多