Reputation: 349
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:
Where the original looks like this:
$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);
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.
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?
Upvotes: 4
Views: 672
Reputation: 41
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
...
Upvotes: 4
Reputation: 1756
this isnt an answer.. it may help you, or it may not
i have tested your code, and work fine for me
also, using your image it wont give me your problem.
as i can see, your result image, that with black border, have a diference with the original.. look the left border, the top dog is croped, and that difference is the black border
Upvotes: 1