2013-12-12 312 views
0

我用gd庫旋轉圖像。 $_POST['rotation']給出旋轉度。 $imagengetWidth()setWidth()getHeight()setHeight()setError()方法的圖像實例:旋轉後獲取新圖像尺寸

//Get the new width and height 
$x = floor(abs($imagen->getWidth() * cos(deg2rad($_POST['rotation'])))) + floor(abs($imagen->getHeight() * sin(deg2rad($_POST['rotation'])))); 
$y = floor(abs($imagen->getWidth() * sin(deg2rad($_POST['rotation'])))) + floor(abs($imagen->getHeight() * cos(deg2rad($_POST['rotation'])))); 

//Set the new width and height   
$imagen->setHeight($y); 
$imagen->setWidth($x); 

//Rotate image 
if(!$canvas = imagerotate ($canvas, $_POST['rotation'], 0)) $imagen->setError('Error rotating'); 

的問題是,有時$x$y變量沒有正確的價值觀。 例如如果我旋轉100º,則獲得$x = 2364,但畫布寬度爲2362.

我在做什麼錯了?

更新:

我試着floor,反之亦然,以取代abs,並得到怪異的結果:

echo 'abs(floor) = '. (abs(floor($imagen->getAncho() * cos(deg2rad($_POST['rotacion'])))) + abs(floor($imagen->getAlto() * sin(deg2rad($_POST['rotacion']))))); 
echo 'floor(abs) = '.(floor(abs($imagen->getAncho() * cos(deg2rad($_POST['rotacion']))))+ floor(abs($imagen->getAlto() * sin(deg2rad($_POST['rotacion']))))); 

結果:

abs(floor) = 2365 floor(abs) = 2364 

我不我真的明白爲什麼abs()會改變這個值。 無論如何,真實值比floor(abs)值小2個像素。

回答

0

其實,我沒能理解下面的行爲,但我發現了一個更簡單的解決方案:把畫布大小,而不是計算它:

if(!$canvas = imagerotate ($canvas, $_POST['rotation'], 0)) $imagen->setError('Error rotating'); 
//Set the new width and height   
$imagen -> setHeight(imagesy($canvas)); 
$imagen -> setWidth(imagesx($canvas)); 

就是這樣!

0

問題是您正在使用floor。相反,你應該使用ceil,向上舍入數字。由於您正在舍入2個數字downwrds(floor),因此可能會錯過2個像素。

即2.5像素需要上顯示3個像素,而不是僅僅2

+0

問題恰恰相反。在這個例子中,我得到2364寬度,但圖像寬度爲2362。 – Manolo

+0

我的不好,我讀錯了!讓我檢查 –

+0

我不確定imagerotate本身使用了哪些計算方法,但我現在可以想象的唯一方法就是在將圖像的值設置爲絕對值之前對圖像進行輪轉(樓層),因此您可以嘗試交換樓板和絕對座標並測試如果它更好... –