Home > front end >  How to rotate a image and save in folder in php?
How to rotate a image and save in folder in php?

Time:05-12

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?

CodePudding user response:

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);

CodePudding user response:

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.

  •  Tags:  
  • php
  • Related