2016-11-16 173 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度的旋转(不要问),同样的边框出现。 –