2016-11-16 42 views
3

我想旋轉並保存圖像。旋轉是基於EXIF數據。我曾嘗試以下,而這一切給黑色邊框周圍:PHP - 用GD旋轉圖像產生黑色邊框

enter image description here

凡原來看起來像這樣:

$orientation = array_values([0, 0, 0, 180, 0, 0, -90, 0, 90])[@exif_read_data($imagePath)['Orientation'] ?: 0]; 

$source = imagecreatefromjpeg($imagePath); 
$resource = imagerotate($source, $orientation, 0); 
imagejpeg($resource, $image, 100); 

我也嘗試添加imagealphablending($resource, true);imagesavealpha($resource, true);建議在Black background when rotating image with PHP,但無濟於事;邊界仍然存在。

然後我試圖與imagecreatetruecolor()創建圖像:

$imageSizes = getimagesize($image); 
$oldWidth = $imageSizes[0]; 
$oldHeight = $imageSizes[1]; 

$orientation = array_values([0, 0, 0, 180, 0, 0, -90, 0, 90])[@exif_read_data($image)['Orientation'] ?: 0]; 

$source = imagecreatefromjpeg($imagePath); 
$resource = imagerotate($source, $orientation, 0); 

$newWidth = $oldWidth; 
$newHeight = $oldHeight; 

if ($orientation !== 180 && $orientation !== 0) { 
    $newWidth = $oldHeight; 
    $newHeight = $oldWidth; 
} 

$imageResized = imagecreatetruecolor($newWidth, $newHeight); 

imagecopyresampled ($imageResized, $resource, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight); 
imagejpeg($imageResized, $image, 100); 

但我似乎無法得到它的工作。有人能幫助我嗎?

回答

1

這個心不是一個答案..它可以幫助你,也可能不會

我已經測試你的代碼,我enter image description here

也做工精細,用你的形象,它不會給我你的問題。

我所看到的,你的結果圖像,與黑色的邊框,與原來的一個性差異。看左邊框,頂部狗croped,而這種差距是黑色邊框

+0

謝謝您的測試。這隻能意味着我正在工作的應用程序會改變其他地方的圖像。我會試着找出在哪裏,但至少我知道這個代碼正在工作:-) –

3

我今天在PHP for Windows中發現了這個問題。當您進行0或360度旋轉時,邊界似乎只會被添加。我沒有180度旋轉的邊界。所以,只需檢查方向是否爲非零,並且只在必要時旋轉。

... if ($orientation !== 0) $resource = imagerotate($source, $orientation, 0); else $resource = $source; end ...

+0

或者如果你正在做一個450度的旋轉(不要問),同樣的邊框出現。 –