PHP-使用GD旋转图像会产生黑色边框 [英] PHP - Rotate image with GD gives black borders
问题描述
我正在尝试旋转并保存图像.旋转基于EXIF数据.我尝试了以下方法,它们周围都有黑色边框:
I am trying to rotate and save an image. The rotation is based on the EXIF data. I have tried the following, which all give a black border around it:
原始图片如下:
$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);
用PHP旋转图片时出现黑色背景,但无济于事;边界仍然存在.
I have also tried adding imagealphablending($resource, true);
and imagesavealpha($resource, true);
as proposed in Black background when rotating image with PHP, but to no avail; the border remains.
然后我尝试使用imagecreatetruecolor()
创建图像:
Then I tried creating the image with 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);
但是我似乎无法正常工作.有人可以帮助我吗?
But I just can't seem to get it work. Is anyone able to help me with this?
推荐答案
我今天在Windows版PHP中发现了此问题.仅当您进行0或360度旋转时才添加边框.我没有旋转180度的边界.因此,只需检查方向是否为非零值,并在必要时才旋转.
I've found this problem today in PHP for Windows. The borders only seem to get added when you do a 0 or 360 degree rotation. I don't get the borders with a 180 degree rotation. So, just check to see if orientation is non-zero and only rotate if necessary.
...
if ($orientation !== 0)
$resource = imagerotate($source, $orientation, 0);
else
$resource = $source;
end
...
...
if ($orientation !== 0)
$resource = imagerotate($source, $orientation, 0);
else
$resource = $source;
end
...
这篇关于PHP-使用GD旋转图像会产生黑色边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!