4

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:

enter image description here

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?

2 Answers 2

4

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 ...

1
  • Or if you're doing a rotation for 450 degrees (don't ask), same border appears. Commented Oct 23, 2017 at 22:43
1

this isnt an answer.. it may help you, or it may not

i have tested your code, and work fine for meenter image description here

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

1
  • Thank you for testing. That could only mean that the application I am working in alters the image somewhere else. I will try to find out where, but at least I know that this code is working :-) Commented Nov 17, 2016 at 8:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.