-1

I want to rotate a image and save it to the folder using php. How can I achieve that?

The code I have tried so far

$filename = 'pexels-philip-justin-mamelic-2872667.jpg';
$degrees = 180;
header('Content-type: image/jpeg');
$source = imagecreatefromjpeg($filename);
$rotate = imagerotate($source, $degrees, 0);
imagedestroy($source);
imagedestroy($rotate);

How to save the image and see if it the rotation is working?

Sarkar
  • 61
  • 2
  • 12
  • 1
    Use `imagejpeg`. See https://www.php.net/manual/de/function.imagejpeg.php – schmauch May 12 '22 at 05:53
  • With the above, without `imagejpeg`, you do not actually save the generated image so the operations probably succeeded but changes are not stored. – Professor Abronsius May 12 '22 at 06:08
  • Does this answer your question? [How to save the rotation of an image on server?](https://stackoverflow.com/questions/46073623/how-to-save-the-rotation-of-an-image-on-server) – kmoser May 12 '22 at 06:36
  • Does this answer your question? [How to rotate image and save the image](https://stackoverflow.com/questions/11259881/how-to-rotate-image-and-save-the-image) – Don't Panic May 12 '22 at 06:49

2 Answers2

0

So remove:

// header('Content-type: image/jpeg');

and add:

imagejpeg($rotate, 'rotated-image-name.jpg', 80);

Working code:

$filename = 'pexels-philip-justin-mamelic-2872667.jpg';
$degrees = 180;
// header('Content-type: image/jpeg');
$source = imagecreatefromjpeg($filename);
$rotate = imagerotate($source, $degrees, 0);
imagejpeg($rotate, 'rotated-image-name.jpg', 80);
imagedestroy($source);
imagedestroy($rotate);
0

You can achieve this by using any image Processing and Generation libraries like Imagick/ GD

Example with GD

You have to use imagerotate function in this cause

Code sample to rotate an image to 180 degree using GD.

$sourceImage = imagecreatefromjpeg('test-design-image.jpg');
$rotateImage = imagerotate($source, 180, 0);
$saveImage = imagejpeg($rotate, 'test-design-rotated.jpg');
imagedestroy($sourceImage);
imagedestroy($rotateImage);

You can use Imagick library also if this library is available with your php.

Example with Imagick::rotateImage

$sourceImage = new Imagick('test-design-image.jpg');
$sourceImage->rotateImage(new \ImagickPixel(), 180);


$sourceImage->writeImage ("test-design-rotated.jpg"); // if it fails, use the 
following method
file_put_contents ("test-design-rotated.jpg", $sourceImage);

Imagick may not installed by default with most php and wampp/lampp/xampp installations. You can check with phpinfo() to verify that Imagick is installed or not.