2012-10-05 96 views
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版本O的图像。它应该垂直和水平居中(基本上获得图像的主要200px)

是可能的吗?

CNC中

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

尝试

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); 
+0

请检查编辑,你的意思是? –

+0

@ToniMichelCaubet现在尝试 – Musa

+0

http://209.51.221.243/integracion/files/uploads/1_2012-09-26%2023.11.55.jpg为什么还会出现黑洞? –