How to rotate an image using php?

Photo of author
Written By geekerhub

Lorem ipsum dolor sit amet consectetur pulvinar ligula augue quis venenatis. 

In order to rotate an image, we need to use different functions based on pathinfo extenstion of the image.

PHP functions used to rotate the image

Below is the simple code snippet that will be helpful to rotate the image by passing the path to the image and by what degree you need to rotate the image.

  function image_rotation($filename, $degrees = 90){
      //User this for jpg images
    	if (preg_match("/jpg|jpeg/", pathinfo($filename, PATHINFO_EXTENSION))){
          $image_source = imagecreatefromjpeg($filename);
          $rotate = imagerotate($image_source, $degrees, 0);
          imagejpeg($rotate, $filename);


      //User this for png images
      if (preg_match("/png/", pathinfo($filename, PATHINFO_EXTENSION))){
         $image_source = imagecreatefrompng($filename);
         $rotate = imagerotate($image_source, $degrees, 0);
         imagepng($rotate, $filename);

      //User this for gif images
      if (preg_match("/gif/", pathinfo($filename, PATHINFO_EXTENSION))){
         $image_source = imagecreatefromgif($filename);
         $rotate = imagerotate($image_source, $degrees, 0);
         imagepng($rotate, $filename);

      imagedestroy($image_source); //free up the memory
      imagedestroy($rotate);  //free up the memory
  image_rotation('/opt/lampp/htdocs/wp-momin/wp-content/plugins/lumise-customization/lumise/1649306773-lumise_print_front.png', 180);

Leave a Comment