2011-07-31 88 views
10

我想從200 * 130大小的中心裁剪圖像要裁剪的圖像的大小可能會有所不同,如果圖像較小,我們不會裁剪它我知道如何在這部分我可以檢查高度和圖像,但種類從圖像的中間被裁剪的東西 因爲我不知道如何保持中心作爲作物點和比向外作物它從中心裁剪圖像PHP

回答

31

GD從4.3.6版本開始捆綁所有的PHP安裝,所以很有可能你有它。

這裏有您需要採取的步驟......

  1. 創建使用的GD imagecreatefrom*()功能之一的圖像資源。您使用的一個取決於你處理
  2. 圖像的類型使用imagesx()imagesy()
  3. 確定你的作物座標使用以下算法和作物使用imagecopy()

查找作物座標確定圖像尺寸

$width = imagesx($img); 
$height = imagesy($img); 
$centreX = round($width/2); 
$centreY = round($height/2); 

$cropWidth = 200; 
$cropHeight = 130; 
$cropWidthHalf = round($cropWidth/2); // could hard-code this but I'm keeping it flexible 
$cropHeightHalf = round($cropHeight/2); 

$x1 = max(0, $centreX - $cropWidthHalf); 
$y1 = max(0, $centreY - $cropHeightHalf); 

$x2 = min($width, $centreX + $cropWidthHalf); 
$y2 = min($height, $centreY + $cropHeightHalf); 

隨意使用我的圖像處理類,它應該做出一些方面要容易得多 - https://gist.github.com/880506

$im = new ImageManipulator('/path/to/image'); 
$centreX = round($im->getWidth()/2); 
$centreY = round($im->getHeight()/2); 

$x1 = $centreX - 100; 
$y1 = $centreY - 65; 

$x2 = $centreX + 100; 
$y2 = $centreY + 65; 

$im->crop($x1, $y1, $x2, $y2); // takes care of out of boundary conditions automatically 
$im->save('/path/to/cropped/image'); 
+1

帽子關閉,這是驚人的,並出色地工作。THanks – June

+0

在第一個算法中,哪些變量對應於imagecopy()的正確參數? –

+0

@ChrisHarrison請參閱https://gist.github.com/philBrown/880506#file-imagemanipulator-php-L185 – Phil

0

這可能會幫助你。

function cropCentered($img, $w, $h) 
{ 
    $cx = $img->getWidth()/2; 
    $cy = $img->getHeight()/2; 
    $x = $cx - $w/2; 
    $y = $cy - $h/2; 
    if ($x < 0) $x = 0; 
    if ($y < 0) $y = 0; 
    return $img->crop($x, $y, $w, $h); 
} 

我假設你正在使用GD庫。 $ img是GD圖像,$ w和$ h分別是寬度和高度,您希望您的新圖像具有。在你的情況下,$ w = 200,$ h = 130.

+0

不,我沒有GD庫可用我 – June

+1

@June GD包含在大多數PHP安裝,使用'phpinfo()',你很可能看到它 –

+0

你可以幫助我創建上述沒有GD庫和保存圖片? – June

1

jeez,你爲什麼要這麼做呢?只需簡單設置x和y位置的量來裁剪/ 2

$imageSize = getimagesize('thumbnail.png'); 

$croppedImage = imagecrop(imagecreatefrompng('thumbnail.png'), ['x' => 0, 'y' => ($imageSize[1]-$imageSize[0]*(9/16))/2, 'width' => $imageSize[0], 'height' => $imageSize[0]*(9/16)]); 

通知我如何用我的$ IMAGESIZE [0] *(9/16),這也是我在y裁剪經量方向,我從原始圖像高度減去找到裁剪量,然後除以2.如果你想要做同樣的寬度,只需按照相同的步驟。