0

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

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

4

1 回答 1

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);
于 2012-10-05T21:22:13.127 回答