Image Rotation in PHP

Image Rotation PHP

In modern technology, sometimes we need to rotate an image like 90′, 180′, 270′, 360′ etc. It has a very easy technique to do this change in your php code. Follow the below instruction to do image rotation php.

Image Rotation PHP

Example Code

                $deg = 90; //Suppose, we want to rotate 90 degree
                $img = 'natural.jpg'; // Image name

                $arr = explode("/",$img);
                $imgname = $arr[count($arr)-1];
                $arr = explode(".",$imgname);
                $ext = $arr[count($arr)-1];

                $file_path = 'root/images/natural.jpg'; // Your file directory path

                if($ext=='jpg' or $ext=='jpeg')
                {
                    ob_start();
                    $source = imagecreatefromjpeg($file_path) or notfound();
                    $rotate = imagerotate($source,$deg,0);
                    ob_end_clean();
                    imagejpeg($rotate,$file_path);
                }
                else if($ext=='png')
                {
                    ob_start();
                    $source = imagecreatefrompng($file_path) or notfound();
                    $transparency = imagecolorallocatealpha( $source,0,0,0,127 );
                    $rotate = imagerotate($source,$deg,$transparency);
                    imagealphablending( $rotate, false );
                    imagesavealpha( $rotate, true );
                    ob_end_clean();
                    imagepng($rotate,$file_path);                
                }
                
                imagedestroy( $source );
                imagedestroy( $rotate );