Rotate an image in PHP

August 23, 2014 | Last tested: June 2015 | 704 views | Comments

Use the function imagerotate() to rotate an image in PHP.

For example.

Rotate a JPEG image to 180 degrees and display the result on the browser.

//the image to be rotated
$image = 'create-a-dark-forest-scene-photo-manipulation.jpg';

//rotation angle
$degrees = 180;

//load the image
$source = imagecreatefromjpeg($image);

//rotate the image
$rotate = imagerotate($source, $degrees, 0);

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

//display the rotated image on the browser
imagejpeg($rotate);

//free the memory
imagedestroy($source);
imagedestroy($rotate);

Result.

Please mouse over here to view the image.

 

To save the new rotated image to a new file.

  • Change this code:
  • 
    //set the Content type
    header('Content-type: image/jpeg');
    
    //display the rotated image on the browser
    imagejpeg($rotate);
    
  • To this:
  • 
    //create the new rotated image
    imagejpeg($rotate,'create-a-dark-forest-scene-photo-manipulation_rotated.jpg');
    

 

Related Tutorials


Must Read